def setUp(self): self.chess = Chess() self.chess.setSquare('b2', 'WP') self.chess.setSquare('c2', 'WP') self.chess.setSquare('c3', 'BP') self.chess.setSquare('d2', 'WP') self.chess.setSquare('d3', 'WP')
def setUp(self): self.chess = Chess() self.chess.setSquare('e1', 'WK') self.chess.setSquare('f3', 'BN') self.chess.setSquare('c4', 'BB') self.chess.setSquare('d8', 'BR') self.chess.setSquare('a2', 'WP')
def test_play_to_checkmate(self): prints = ["Check!", "Checkmate"][::-1] def test_print(statement): self.assertEqual(prints.pop(), statement) inputs = ["Make move:", "Make move:", "Make move:", "Make move:", "Make move:", "Make move:", "Make move:"][::-1] prompts = ["PE2E4", "PE7E5", "BF1C4", "NB8C6", "QD1F3", "PB7B6", "QF3F7"][::-1] def test_input(statement): self.assertEqual(inputs.pop(), statement) return prompts.pop() Chess.play(test_print, test_input)
def __init__(self, type_of_game: str, game_id: str, ip1: str, ip2: str): invoker = Invoker() if type_of_game == 'chess': game = Chess(game_id, ip1) elif type_of_game == 'dga': game = DontGetAngry(game_id, ip1, ip2) else: return while game.is_looping: inp = input('What\'s your next command?\n') args = inp.split(' ') command = args[0] arg = args[1] if len(args) == 2 else None if command == '/display': invoker.set_command(Display(game)) elif command == '/move': invoker.set_command(Move(game, arg)) elif command == '/turnof': invoker.set_command(TurnOf(game)) elif command == '/whoami': invoker.set_command(WhoAmI(game)) elif command == '/allowed': invoker.set_command(Allowed(game)) elif command == '/dinfo': invoker.set_command(GInfo(game)) elif command == '/ff': invoker.set_command(Forfeit(game)) elif command == '/status': invoker.set_command(Status(game)) elif command == '/fetch': invoker.set_command(Fetch(game)) elif command == '/refresh': invoker.set_command(Refresh(game)) invoker.do() if type_of_game == 'chess': game = Chess(game_id, ip1) elif type_of_game == 'dga': game = DontGetAngry(game_id, ip1, ip2) else: return continue elif command == '/q': print('See you again!') sys.exit(0) else: print('Wrong command, please try again.') invoker.do()
def SetChess(self, x, y): if self.NotInBoard(x, y, self.n): return False if self.board[x, y] != 0: return False if x == y and x == int((self.n - 1) / 2): return False white = Chess(x, y, 1) self.white.append(white) self.board[x, y] = 1 xx = self.n - 1 - x yy = self.n - 1 - y black = Chess(xx, yy, -1) self.black.append(black) self.board[xx, yy] = -1
def fromString(cls, source, owner): from Rule import MAXINITCHESS from Rule import MAXCHESS from Rule import canPlace ret = Layout(owner) count = list(Chess.InitNum) p = source.strip().split() if len(p) != MAXINITCHESS: raise ValueError("Invalid layout string %s" %(source)) pos = 0 for valstr in p: val = int(valstr.strip()) ch = Chess(val, owner) if not canPlace( ret, pos, ch ): raise ValueError( "Invalid layout string %s" %(source) ) else: ret.setChess( pos, ch ) count[val] -= 1 if count[val] < 0: raise ValueError( "Invalid layout string %s" %(source) ) pos += 1 if pos >= MAXCHESS: break while ret.getPos( pos ).isSafe(): ret.setChess( pos, None ) pos += 1 return ret
def setToDefault( self ): pos = 0 for value in Layout.defaultLayout: self.setChess( pos, Chess( value, self.player ) ) pos += 1 if pos >= self.getSize(): break while self.getPos( pos ).isSafe(): self.setChess( pos, None ) pos += 1
class ChessGame: def __init__(self): """Initializes chess class and board""" self.chess = Chess() def startGame(self): """Starts the interactive chess game and runs the game loop""" print("Welcome to Chess!") print("Input 'q' to exit game") print("Input 'm' to see moves made so far") print("Input 'g' to toggle glyph for chess pieces") print( "Unambiguous moves are accepted in algebraic chess notation\n\tEx: Nf3, e4, Rxa7, f8=Q" ) print( "Moves are also accepted in long algebraic chess notation\n\tEx: Ng1-f3, e2-e4, Ra4xa7, f7-f8=Q" ) print("\n") self.chess.setupBoard() self.gameLoop() def gameLoop(self): """Runs the game loop, asking for input and exiting on 'q' input""" while True: self.chess.printBoard() try: input_query = '' if self.chess.turn == 0: input_query = 'White to move > ' else: input_query = 'Black to move > ' moveInput = input(input_query) if moveInput == 'q': return elif moveInput == 'm': self.chess.printMoves() continue elif moveInput == 'g': self.chess.glyphs = not self.chess.glyphs continue self.chess.makeMove(moveInput.strip()) except ValueError as err: print(err)
def __init__(self, master, canvas): self.master = master self.cv = canvas self.bg_image = tk.PhotoImage(file="images/chess_bg.png") self.chess = Chess() # Event listeners response self.moves = [] self.circles = [] self.piece_clicked = False self.current_piece = None # Binding to get click events self.master.bind("<Button-1>", self.getClickXY) self.white_turn = True self.piece_clicked = False self.piece_images = [] # Prints board and loads pieces self.print_board() self.drawPieces()
def gameLoop(): running = True background = BLACK mx, my = pygame.mouse.get_pos() count = 0 ox = 50 oy = 50 c_width = (width - 2 * ox) / 8 c_height = (height - 2 * oy) / 8 m_active = False active_cell = None action_cell = None active_time = 0 action_time = 0 CHESS_DARK_MAROON = (59, 39, 71) CHESS_LIGHT_MAROON = (100, 106, 158) CHESS_BROWN = (209, 139, 71) CHESS_WHITE = (255, 206, 158) DARK_CELL_COLOR = CHESS_DARK_MAROON LIGHT_CELL_COLOR = CHESS_LIGHT_MAROON game = Chess() board = game.board # For each Piece on Board: # Construct a Image representation for index in range(0, len(board.board)): # Create Image for each corresponding Piece => Image piece = board[index] #piece.id = 0 asset_name = Piece.make_asset_name(piece.representation) if asset_name is not Piece.Piece.EMPTY: # piece.image = GPiece(assets[asset_name], piece.position) piece.sprite = GPiece(piece) else: piece.sprite = Piece.Piece.EMPTY while running: mx, my = pygame.mouse.get_pos() # Draw a Background screen.fill(background) # Draw a Board for r in range(0, 8): for c in range(0, 8): if count % 2 == 0: pygame.draw.rect(screen, DARK_CELL_COLOR, [ ox + c_width * r, oy + c_height * c, c_width, c_height ]) else: pygame.draw.rect(screen, LIGHT_CELL_COLOR, [ ox + c_width * r, oy + c_height * c, c_width, c_height ]) count += 1 count += 1 # Draw Entites queen = pygame.transform.scale(black_pawn, (int(c_width - 30), int(c_height - 10))) outline = pygame.transform.laplacian(black_pawn) rect = queen.get_rect().move(mx, my) pygame.draw.rect(screen, RED, rect, 3) screen.blit(outline, (mx, my, 50, 50)) screen.blit(queen, (mx, my, 50, 50)) # Draw each Piece (GPiece) for piece in board: # print(s.x) if piece.sprite is not Piece.Piece.EMPTY: screen.blit(piece.sprite.image, piece.sprite.rect) # Draw on Board per GPiece if mx >= ox and mx <= c_width * 8 + ox and my >= oy and my <= c_height * 8 + oy: cx = ox + int((mx - ox) / c_width) * c_width cy = oy + int((my - oy) / c_height) * c_height #print(cx) if active_cell and action_cell is None: pygame.draw.rect(screen, RED, [cx, cy, c_width, c_height], 4) elif active_cell is None: pygame.draw.rect(screen, BLUE, [cx, cy, c_width, c_height], 4) # Draw Active Cell if active_cell: ax, ay = active_cell cx = ax * c_width + ox cy = ay * c_height + oy piece = board.get_piece_2d((ax, ay)) pygame.draw.rect(screen, GREEN, [cx, cy, c_width, c_height], 4) if pygame.time.get_ticks() - active_time > 2200: # print("~Activated X~") active_cell = None if action_cell: ax, ay = action_cell cx = ax * c_width + ox cy = ay * c_height + oy pygame.draw.rect(screen, RED, [cx, cy, c_width, c_height], 4) if pygame.time.get_ticks() - action_time > 2200: # print("~Activated X~") action_cell = None # If active, and action cell # if active_cell and action_cell: # Update Application Logic if active_cell and action_cell: ax, ay = active_cell cx = math.floor((mx - ox) / c_width) cy = math.floor((my - oy) / c_height) the_piece = board.get_piece_2d(active_cell) other_piece = board.get_piece_2d(action_cell) # Apply Game Logic # Update in Graphical Components the_sprite = the_piece.sprite other_sprite = other_piece.sprite print('transposing : ', the_sprite.x) the_sprite.set_board_position(*other_piece.position) if other_piece.id is not Piece.Piece.EMPTY: other_sprite.set_board_position(*the_piece.position) # Update on Board Model board.transpose_piece(the_piece, other_piece) active_cell = None action_cell = None for piece in board: if piece.sprite is Piece.Piece.EMPTY: continue piece.sprite.update() # Update Display pygame.display.update() import math # Handle Events for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_q: pygame.quit() running = False elif event.key == pygame.K_x: pygame.mouse.set_pos(0, 0) elif event.key == pygame.K_w: DARK_CELL_COLOR = CHESS_BROWN LIGHT_CELL_COLOR = CHESS_WHITE background = GRAY elif event.key == pygame.K_e: DARK_CELL_COLOR = CHESS_DARK_MAROON LIGHT_CELL_COLOR = CHESS_LIGHT_MAROON background = BLACK if event.type == pygame.MOUSEBUTTONDOWN: print("Click...", end='', flush=True) # Current Row/Col Mouse Over ax = math.floor((mx - ox) / c_width) ay = math.floor((my - oy) / c_height) piece = board.get_piece_2d((ax, ay)) print(piece, piece.id, piece.position) # If Click within Board if mx >= ox and mx <= c_width * 8 + ox and my >= oy and my <= c_height * 8 + oy: # If cell active, inactive if active_cell is None: if piece.id != Piece.Piece.EMPTY: active_cell = (ax, ay) # Get Current Time active_time = pygame.time.get_ticks() print("active cell") # Else, check to set Active Cell elif action_cell is None and active_cell != (ax, ay): # Set as Action Cell action_cell = (ax, ay) # Get Current Time action_time = active_time elif active_cell == (ax, ay): active_cell = None action_cell = None if event.type == pygame.MOUSEBUTTONUP: pass if event.type == pygame.QUIT: running = False # Set Frame Rate clock.tick(60)
def __init__(self): """Initializes chess class and board""" self.chess = Chess()
class CheckTests(unittest.TestCase): def setUp(self): self.chess = Chess() self.chess.setSquare('e1', 'WK') self.chess.setSquare('f3', 'BN') self.chess.setSquare('c4', 'BB') self.chess.setSquare('d8', 'BR') self.chess.setSquare('a2', 'WP') def test_moving_in_check(self): """ No moving into check """ with self.assertRaises(ValueError): self.chess.makeMove('a3') with self.assertRaises(ValueError): self.chess.makeMove('Ke2') with self.assertRaises(ValueError): self.chess.makeMove('Kd1') self.chess.makeMove('Kf2') self.assertEqual(self.chess.checkSquare('e1'), EMPTY_SQUARE) self.assertEqual(self.chess.checkSquare('f2'), 'WK') def test_pinned_check(self): """ No moving pinned piece into check """ self.chess.setSquare('f3', 'WN') self.chess.setSquare('b4', 'BQ') self.chess.setSquare('d2', 'WR') with self.assertRaises(ValueError): self.chess.makeMove('Rd6') self.chess.makeMove('a3') self.assertEqual(self.chess.checkSquare('d6'), EMPTY_SQUARE) self.assertEqual(self.chess.checkSquare('d2'), 'WR') def test_pawn_check1(self): """ No allowing pawn checks """ self.chess.setSquare('f3', 'WN') self.chess.setSquare('f2', 'BP') self.chess.setSquare('e2', 'BP') with self.assertRaises(ValueError): self.chess.makeMove('a3') self.chess.makeMove('Kxf2') self.assertEqual(self.chess.checkSquare('e1'), EMPTY_SQUARE) self.assertEqual(self.chess.checkSquare('f2'), 'WK') def test_pawn_check2(self): """ King not in check in front of pawn """ self.chess.setSquare('f3', 'WN') self.chess.setSquare('e2', 'BP') self.chess.makeMove('a3') def test_block_check(self): """ Check should be able to be blocked """ self.chess.setSquare('f3', 'WN') self.chess.setSquare('b4', 'BQ') self.chess.setSquare('g5', 'WB') self.chess.makeMove('Bd2')
def Game(): chess = Chess() print(chess.getBoard()) gui = GUI(chess)
class PawnPromotionTest(unittest.TestCase): def setUp(self): self.chess = Chess() self.chess.setSquare('e7', 'WP') self.chess.setSquare('e2', 'BP') self.chess.setSquare('f1', 'WN') def test_promotion(self): """ Pawn promotion """ with self.assertRaises(ValueError): self.chess.makeMove('e8') with self.assertRaises(ValueError): self.chess.makeMove('exf8') self.chess.makeMove('e8=N') with self.assertRaises(ValueError): self.chess.makeMove('exf1') with self.assertRaises(ValueError): self.chess.makeMove('exf1=K') self.chess.makeMove('exf1=Q') self.assertEqual(self.chess.checkSquare('e7'), EMPTY_SQUARE) self.assertEqual(self.chess.checkSquare('e8'), 'WN') self.assertEqual(self.chess.checkSquare('e2'), EMPTY_SQUARE) self.assertEqual(self.chess.checkSquare('e1'), EMPTY_SQUARE) self.assertEqual(self.chess.checkSquare('f1'), 'BQ') def test_not_promotion(self): """ Not promotios """ self.chess.setSquare('e8', 'BB') self.chess.setSquare('a2', 'WP') with self.assertRaises(ValueError): self.chess.makeMove('Ne3=R') with self.assertRaises(ValueError): self.chess.makeMove('e8=B') with self.assertRaises(ValueError): self.chess.makeMove('a4=Q')
import pygame from Chess import Chess pygame.init() display_width = 600 display_height = 600 MAP_SIZE = 8 part = (display_width / MAP_SIZE, display_height / MAP_SIZE) clock = pygame.time.Clock() gameDisplay = pygame.display.set_mode((display_width, display_height)) gameAPI = Chess() image = { "♔": pygame.image.load("image/king_white.png"), "♘": pygame.image.load("image/knight_white.png"), "♕": pygame.image.load("image/queen_white.png"), "♖": pygame.image.load("image/rook_white.png"), "♙": pygame.image.load("image/pawn_white.png"), "♗": pygame.image.load("image/bishop_white.png"), "♚": pygame.image.load("image/king_black.png"), "♞": pygame.image.load("image/knight_black.png"), "♛": pygame.image.load("image/queen_black.png"), "♜": pygame.image.load("image/rook_black.png"), "♟": pygame.image.load("image/pawn_black.png"), "♝": pygame.image.load("image/bishop_black.png") } rect1 = pygame.Rect((0, 0, 30, 30))
class PawnMovesTest(unittest.TestCase): def setUp(self): self.chess = Chess() self.chess.setSquare('b2', 'WP') self.chess.setSquare('c2', 'WP') self.chess.setSquare('c3', 'BP') self.chess.setSquare('d2', 'WP') self.chess.setSquare('d3', 'WP') def test_illegal_hop1(self): """ Illegal pawn hopping over other color """ with self.assertRaises(ValueError): self.chess.makeMove('c4') self.assertEqual(self.chess.checkSquare('c2'), 'WP') self.assertEqual(self.chess.checkSquare('c3'), 'BP') self.assertEqual(self.chess.checkSquare('d2'), 'WP') self.assertEqual(self.chess.checkSquare('d3'), 'WP') self.assertEqual(self.chess.checkSquare('c4'), EMPTY_SQUARE) def test_illegal_hop2(self): """ Illegal pawn hopping over same color """ with self.assertRaises(ValueError): self.chess.makeMove('d2-d4') self.assertEqual(self.chess.checkSquare('c2'), 'WP') self.assertEqual(self.chess.checkSquare('c3'), 'BP') self.assertEqual(self.chess.checkSquare('d2'), 'WP') self.assertEqual(self.chess.checkSquare('d3'), 'WP') self.assertEqual(self.chess.checkSquare('d4'), EMPTY_SQUARE) def test_move_correct_pawn(self): """ Move correct pawn of doubled pawns """ self.chess.makeMove('d4') self.assertEqual(self.chess.checkSquare('c2'), 'WP') self.assertEqual(self.chess.checkSquare('c3'), 'BP') self.assertEqual(self.chess.checkSquare('d2'), 'WP') self.assertEqual(self.chess.checkSquare('d4'), 'WP') self.assertEqual(self.chess.checkSquare('d3'), EMPTY_SQUARE) def test_move_illegal_capture_input1(self): """ Illegal capture input """ with self.assertRaises(ValueError): self.chess.makeMove('c3') self.assertEqual(self.chess.checkSquare('c2'), 'WP') self.assertEqual(self.chess.checkSquare('c3'), 'BP') self.assertEqual(self.chess.checkSquare('d2'), 'WP') self.assertEqual(self.chess.checkSquare('d3'), 'WP') def test_move_illegal_capture_input2(self): """ Illegal capture input """ with self.assertRaises(ValueError): self.chess.makeMove('axc3') self.assertEqual(self.chess.checkSquare('c2'), 'WP') self.assertEqual(self.chess.checkSquare('c3'), 'BP') self.assertEqual(self.chess.checkSquare('d2'), 'WP') self.assertEqual(self.chess.checkSquare('d3'), 'WP') def test_move_capture_input1(self): """ Capture input dxc3 """ self.chess.makeMove('dxc3') self.assertEqual(self.chess.checkSquare('b2'), 'WP') self.assertEqual(self.chess.checkSquare('c2'), 'WP') self.assertEqual(self.chess.checkSquare('c3'), 'WP') self.assertEqual(self.chess.checkSquare('d2'), EMPTY_SQUARE) self.assertEqual(self.chess.checkSquare('d3'), 'WP') def test_move_capture_input2(self): """ Capture input bxc3 """ self.chess.makeMove('bxc3') self.assertEqual(self.chess.checkSquare('b2'), EMPTY_SQUARE) self.assertEqual(self.chess.checkSquare('c2'), 'WP') self.assertEqual(self.chess.checkSquare('c3'), 'WP') self.assertEqual(self.chess.checkSquare('d2'), 'WP') self.assertEqual(self.chess.checkSquare('d3'), 'WP')
def setUp(self): self.chess = Chess() self.chess.setupBoard()
def setUp(self): self.chess = Chess() self.chess.setSquare('e7', 'WP') self.chess.setSquare('e2', 'BP') self.chess.setSquare('f1', 'WN')
from tkinter import * from Chess import Chess from AIBlackLoops import AIBlackLoops from AIMinimaxAlphaBeta import AIMinimaxAlphaBeta import cProfile # create global variables chess = Chess() # AI = AIBlackLoops() AI = AIMinimaxAlphaBeta() row = 1 # row of where you last clicked col = 1 # col of where you last clicked def click(event): x, y = event.x, event.y global row global col r, c = x_y_to_row_col(x, y) row = r col = c draw_piece_white(x, y, chess.board_unique[row, col]) def holding(event): x, y = event.x, event.y draw_piece_white(x, y, chess.board_unique[row, col]) def release(event): global chess
from Chess import Chess chess = Chess() print(chess.get_simple_password("wtnhxymk")) # 2414bc77 print(chess.get_enhanced_password("wtnhxymk")) # 437e60fc
from Chess import Chess if __name__ is "__main__": # Start a Game chess = Chess() chess.play()
import discord import Functions import asyncio from Chess import Chess client = discord.Client() test = Chess() lun = '<@!720307801091735623>' mlun = '<@720307801091735623>' @client.event async def on_ready(): await client.change_presence(activity=discord.Game( name='smarter than you | @Lun')) @client.event async def on_message(message): message.content = message.content.lower() async def print_formatted_board(formatted_board): split_board = formatted_board.split('\n') split_board.remove('') if test.white_turn: for i in range(len(split_board)): await message.channel.send(split_board[i] + Chess.rank_list[7 - i]) await message.channel.send(Chess.white_files) else: for i in range(len(split_board)):
def setToUnknown( self ): for Pos in self.item: if Pos.isSafe(): Pos.setChess( None ) else: Pos.setChess(Chess( 0, self.player ) )
class CastlingTest(unittest.TestCase): """ Tests for Castling """ def setUp(self): self.chess = Chess() self.chess.setSquare('e1', 'WK') self.chess.setSquare('h1', 'WR') self.chess.setSquare('e8', 'BK') self.chess.setSquare('a8', 'BR') def test_castling(self): """ Test castling """ self.chess.makeMove('O-O') self.chess.makeMove('O-O-O') self.chess.printBoard() self.assertEqual(self.chess.checkSquare('e1'), EMPTY_SQUARE) self.assertEqual(self.chess.checkSquare('f1'), 'WR') self.assertEqual(self.chess.checkSquare('g1'), 'WK') self.assertEqual(self.chess.checkSquare('h1'), EMPTY_SQUARE) self.assertEqual(self.chess.checkSquare('e8'), EMPTY_SQUARE) self.assertEqual(self.chess.checkSquare('d8'), 'BR') self.assertEqual(self.chess.checkSquare('c8'), 'BK') self.assertEqual(self.chess.checkSquare('b8'), EMPTY_SQUARE) self.assertEqual(self.chess.checkSquare('a8'), EMPTY_SQUARE) def test_blocked_castle(self): """ Test blocked castling """ self.chess.setSquare('f1', 'WB') with self.assertRaises(ValueError): self.chess.makeMove('0-0') self.chess.makeMove('Be2') self.chess.makeMove('0-0-0') self.chess.makeMove('0-0') def test_moved_before_castle(self): """ Test illegal castling after moving pieces """ self.chess.setSquare('a1', 'WR') self.chess.makeMove('Rh2') self.chess.makeMove('Ke7') self.chess.makeMove('Rh1') self.chess.makeMove('Ke8') with self.assertRaises(ValueError): self.chess.makeMove('0-0') self.chess.makeMove('0-0-0') with self.assertRaises(ValueError): self.chess.makeMove('0-0-0') def test_castle_out_of_check(self): """ Test illegal castling out of check """ self.chess.setSquare('e4', 'BQ') with self.assertRaises(ValueError): self.chess.makeMove('0-0') with self.assertRaises(ValueError): self.chess.makeMove('Rf1') def test_castle_through_check(self): """ Test illegal castling through check """ self.chess.setSquare('f4', 'BQ') self.chess.setSquare('c4', 'WQ') with self.assertRaises(ValueError): self.chess.makeMove('0-0') self.chess.makeMove('Rf1') with self.assertRaises(ValueError): self.chess.makeMove('0-0') def test_castle_into_check(self): """ Test illegal castling into check """ self.chess.setSquare('g4', 'BQ') self.chess.setSquare('b4', 'WQ') with self.assertRaises(ValueError): self.chess.makeMove('0-0') self.chess.makeMove('Rf1') with self.assertRaises(ValueError): self.chess.makeMove('0-0') self.chess.makeMove('Rc8')
class Game: def __init__(self, master, canvas): self.master = master self.cv = canvas self.bg_image = tk.PhotoImage(file="images/chess_bg.png") self.chess = Chess() # Event listeners response self.moves = [] self.circles = [] self.piece_clicked = False self.current_piece = None # Binding to get click events self.master.bind("<Button-1>", self.getClickXY) self.white_turn = True self.piece_clicked = False self.piece_images = [] # Prints board and loads pieces self.print_board() self.drawPieces() def drawPieces(self): for piece_num in range(16): b_piece = self.chess.black_pieces[piece_num] w_piece = self.chess.white_pieces[piece_num] b_x, b_y = self.convert_grid_to_pixel(b_piece.x, b_piece.y) w_x, w_y = self.convert_grid_to_pixel(w_piece.x, w_piece.y) b_img = tk.PhotoImage(file=b_piece.file) w_img = tk.PhotoImage(file=w_piece.file) self.piece_images.append(b_img) self.piece_images.append(w_img) b_id = self.cv.create_image(b_x, b_y, image=b_img, anchor='nw') w_id = self.cv.create_image(w_x, w_y, image=w_img, anchor='nw') b_piece.id = b_id w_piece.id = w_id def getClickXY(self, click_event): x = click_event.x y = click_event.y self.removeCircles() grid_x, grid_y = self.convert_pixel_to_grid(x, y) target_piece = self.chess.matrix[grid_x][grid_y] if self.piece_clicked: self.move_piece(grid_x, grid_y) elif target_piece.color == 'WHITE' and self.white_turn: self.click_piece(grid_x, grid_y) elif target_piece.color == 'BLACK' and not self.white_turn: self.click_piece(grid_x, grid_y) def minimax_AI(self): AI_board = self.chess.clone() depth = 3 alpha = [None, -1000000] # some very large number beta = [None, 1000000] # some very large number best_move = minimax([AI_board, 10000], depth, alpha, beta, True, True) board_obj, board_val, piece_x, piece_y, move_x, move_y = best_move[0] piece = self.chess.matrix[piece_x][piece_y] target_piece = self.chess.matrix[move_x][move_y] piece_move = piece.move(move_x, move_y, self.chess) if len(piece_move) == 4 and piece_move[3]: self.move_visually(piece_x, piece_y, None, piece) self.move_visually(piece_move[0], piece_move[1], None, piece_move[2]) elif len(piece_move) == 2 and piece_move[0] and piece_move[1]: promoted_piece = self.chess.matrix[piece.x][piece.y] promoted_x, promoted_y = self.convert_grid_to_pixel( piece.x, piece.y) promoted_image = tk.PhotoImage(file=promoted_piece.file) self.piece_images.append(promoted_image) promoted_id = self.cv.create_image(promoted_x, promoted_y, image=promoted_image, anchor='nw') promoted_piece.id = promoted_id self.cv.delete(piece.id) if target_piece is not None: self.cv.delete(target_piece.id) elif len(piece_move) == 2 and piece_move[0]: self.move_visually(piece_x, piece_y, target_piece, piece) self.white_turn = not self.white_turn def random_AI(self): pieces = self.chess.black_pieces rand_piece = pieces[random.randint(0, len(pieces) - 1)] moves = rand_piece.possible_grid_moves(self.chess.matrix) while len(moves) == 0: rand_piece = pieces[random.randint(0, len(pieces) - 1)] moves = rand_piece.possible_grid_moves(self.chess.matrix) rand_move = moves[random.randint(0, len(moves) - 1)] piece_move = rand_piece.move(rand_move[0], rand_move[1], self.chess) # needs to be adjusted for the case of castling if piece_move: self.white_turn = not self.white_turn else: self.random_AI() def move_piece(self, grid_x, grid_y): for move in self.moves: if grid_x == move[0] and grid_y == move[1]: target_piece = self.chess.matrix[grid_x][grid_y] prev_x = self.current_piece.x prev_y = self.current_piece.y piece_move = self.current_piece.move(grid_x, grid_y, self.chess) piece = self.current_piece # piece_move = [previous rook x, previous rook y, rook object, boolean # that returns true if castling is legal] if len(piece_move) == 4 and piece_move[3]: self.white_turn = not self.white_turn self.move_visually(prev_x, prev_y, None, self.current_piece) self.move_visually(piece_move[0], piece_move[1], None, piece_move[2]) self.minimax_AI() # piece_move in promotion elif len(piece_move) == 2 and piece_move[0] and piece_move[1]: self.white_turn = not self.white_turn promoted_piece = self.chess.matrix[piece.x][piece.y] promoted_x, promoted_y = self.convert_grid_to_pixel( piece.x, piece.y) promoted_image = tk.PhotoImage(file=promoted_piece.file) self.piece_images.append(promoted_image) promoted_id = self.cv.create_image(promoted_x, promoted_y, image=promoted_image, anchor='nw') promoted_piece.id = promoted_id self.cv.delete(piece.id) if target_piece is not None: self.cv.delete(target_piece.id) self.minimax_AI() # every other move that's not castling or promotion elif len(piece_move) == 2 and piece_move[0]: self.white_turn = not self.white_turn self.move_visually(prev_x, prev_y, target_piece, self.current_piece) self.minimax_AI() self.piece_clicked = False def move_visually(self, x, y, target_piece, this_piece): # If we killed a piece, remove it if target_piece is not None: self.cv.delete(target_piece.id) # Calculate pixel coordinates prev_pixel_x, prev_pixel_y = self.convert_grid_to_pixel(x, y) new_pixel_x, new_pixel_y = self.convert_grid_to_pixel( this_piece.x, this_piece.y) difference_x = new_pixel_x - prev_pixel_x difference_y = new_pixel_y - prev_pixel_y self.cv.move(this_piece.id, difference_x, difference_y) def removeCircles(self): for circle in self.circles: self.cv.delete(circle) def click_piece(self, grid_x, grid_y): self.current_piece = self.chess.matrix[grid_x][grid_y] if (self.current_piece is None): return False self.moves = self.current_piece.possible_moves(self.chess.matrix) self.piece_clicked = True for i in range(len(self.moves)): grid_x, grid_y = self.moves[i] px, py = self.convert_grid_to_pixel(grid_x, grid_y) pixel_x, pixel_y = self.convert_grid_to_pixel( self.current_piece.x, self.current_piece.y) x = [grid_x, grid_y, px, py] r = 10 x0 = x[2] - r + 30 x1 = x[2] + r + 30 y0 = x[3] - r + 30 y1 = x[3] + r + 30 id_num = self.cv.create_oval(x0, y0, x1, y1, fill="#ed7979") self.circles.append(id_num) return True def convert_grid_to_pixel(self, x, y): pos_list = [((x + 1) * 80) + 10, ((y + 1) * 80) + 10] return pos_list def convert_pixel_to_grid(self, x, y): pos_lis = [int(x / 80) - 1, int(y / 80) - 1] return pos_lis def print_board(self): # get the width and height of the image board_width = self.bg_image.width() board_height = self.bg_image.height() # size the window so the image will fill it self.master.geometry('%dx%d+%d+%d' % (board_width, board_height, 600, 100)) self.cv.pack(side='top', fill='both', expand='yes') self.cv.create_image(0, 0, image=self.bg_image, anchor='nw')
def setUp(self): self.chess = Chess() self.chess.setSquare('e1', 'WK') self.chess.setSquare('h1', 'WR') self.chess.setSquare('e8', 'BK') self.chess.setSquare('a8', 'BR')
from Chess import Chess if __name__ == '__main__': Chess().run()
class SimpleInputsTest(unittest.TestCase): def setUp(self): self.chess = Chess() self.chess.setupBoard() def test_move_e4(self): """ Simple e4 chess move """ self.chess.makeMove('e4') self.assertEqual(self.chess.board[1][4], EMPTY_SQUARE) self.assertEqual(self.chess.board[3][4], 'WP') def test_taking_turns(self): """ Turns change only after legal moves """ self.chess.makeMove('e4') self.assertEqual(self.chess.turn, 1) self.chess.makeMove('e5') self.assertEqual(self.chess.turn, 0) with self.assertRaises(ValueError): self.chess.makeMove('e5') self.assertEqual(self.chess.turn, 0) def test_move_e2e4(self): """ Simple e2-e4 chess move """ self.chess.makeMove('e2-e4') self.assertEqual(self.chess.board[1][4], EMPTY_SQUARE) self.assertEqual(self.chess.board[3][4], 'WP') def test_move_e3e4(self): """ Illegal e3-e4 chess move """ with self.assertRaises(ValueError): self.chess.makeMove('e3-e4') self.assertEqual(self.chess.board[1][4], 'WP') self.assertEqual(self.chess.board[3][4], EMPTY_SQUARE) def test_move_Nf3(self): """ Simple Nf3 chess move """ self.chess.makeMove('Nf3') self.assertEqual(self.chess.board[3][4], EMPTY_SQUARE) self.assertEqual(self.chess.board[1][4], 'WP') self.assertEqual(self.chess.board[0][6], EMPTY_SQUARE) self.assertEqual(self.chess.board[2][5], 'WN') def test_bad_input(self): """ Bad input chess move """ with self.assertRaises(ValueError): self.chess.makeMove('nf4') self.assertEqual(self.chess.board[3][4], EMPTY_SQUARE) self.assertEqual(self.chess.board[1][4], 'WP') self.assertEqual(self.chess.board[0][6], 'WN') self.assertEqual(self.chess.board[0][1], 'WN') def test_illegal_move_input(self): """ Bad e5 chess move """ with self.assertRaises(ValueError): self.chess.makeMove('e5') self.assertEqual(self.chess.board[3][4], EMPTY_SQUARE) self.assertEqual(self.chess.board[1][4], 'WP') def test_pos_conv(self): """ Position to array coord conversion """ self.assertEqual(self.chess.convertPosToCoords('a4'), (3, 0)) self.assertEqual(self.chess.convertPosToCoords('g5'), (4, 6))
def pressChess(self): ChessFrame = Chess() ChessFrame.Show()
def setUp(self): self.chess = Chess() self.chess.setSquare('e3', 'WB') self.chess.setSquare('b7', 'BR')