def PossibleMove(board,node,cur_player): # 遍历棋盘格 # node 是父节点 subtree=node subtree.setExpand(True) for i in range(8): for j in range(8): temp_board = copy.deepcopy(board) if temp_board[i][j]==0: # 找到一个可能的起始位置 # 搜索八宫格 flag = 1 pos=Chess.Position(i,j) # 往八个方向搜索,123...8这些代表可能方向 for direction in range(8): num=MoveSearch(temp_board,pos,direction+1,cur_player,0) # 最后的0代表中间没有对手的棋 # print(num) if num!=0 and flag==1: # 说明有一个可能的起始位置 n=Chess.Node() n.player=cur_player n.setPosition(i,j) n.Board=temp_board subtree.add(n) flag=0 # subtree.Expand=True return subtree
def initChess(self): for i in range(0, 4): if (i < 2): self.chesses.append(Chess("BLACK", i * 3 + 3, 0, i)) self.board[i * 3 + 3][0] = i else: self.chesses.append(Chess("BLACK", (i - 2) * 9, 3, i)) self.board[(i - 2) * 9][3] = i for i in range(0, 4): if (i < 2): self.chesses.append(Chess("WHITE", i * 9, 6, i + 4)) self.board[i * 9][6] = i + 4 else: self.chesses.append(Chess("WHITE", (i - 1) * 3, 9, i + 4)) self.board[(i - 1) * 3][9] = i + 4 for chess in self.chesses: chess.piece = LaBel(self.wd) chess.piece.setVisible(True) # 图片可视 chess.piece.setScaledContents(True) # 图片大小根据标签大小可变 if (chess.type == "WHITE"): chess.piece.setPixmap(self.white) # 放置白色棋子 else: chess.piece.setPixmap(self.black) chess.piece.setGeometry(chess.x * RECT + BORDER, chess.y * RECT + BORDER, RECT - 3, RECT - 3)
def test_remove(self): wking = Chess.Piece(1, "E", True, Chess.PieceType.king, True) bking = Chess.Piece(8, "E", True, Chess.PieceType.king, False) self.board.addpiece(wking) self.board.addpiece(bking) self.logic.remove(wking, self.board) self.assertFalse(wking.active) self.assertTrue( self.board.getpos(5, 1).gettype() == Chess.PieceType.empty)
def test_getValidKingMoves(self): wking = Chess.Piece(1, "E", True, Chess.PieceType.king, True) bking = Chess.Piece(8, "E", True, Chess.PieceType.king, False) wking2 = Chess.Piece(4, "E", True, Chess.PieceType.king, True) wking3 = Chess.Piece(8, "H", True, Chess.PieceType.king, True) wking4 = Chess.Piece(4, "H", True, Chess.PieceType.king, True) wpawn = Chess.Piece(7, "E", True, Chess.PieceType.pawn, True) bpawn = Chess.Piece(7, "D", True, Chess.PieceType.pawn, False) wrook = Chess.Piece(1, "A", True, Chess.PieceType.rook, True) wrook2 = Chess.Piece(1, "H", True, Chess.PieceType.rook, True) self.board.addpieces(wking, bking, wking2, wking3, wking4, wpawn, bpawn, wrook, wrook2) wkingmoves = [((5, 1), (6, 1)), ((5, 1), (6, 2)), ((5, 1), (4, 1)), ((5, 1), (4, 2)), ((5, 1), (5, 2)), ((5, 1), (7, 1, Chess.SpecialMove.king_castle)), ((5, 1), (3, 1, Chess.SpecialMove.queen_castle))] bkingmoves = [((5, 8), (6, 8)), ((5, 8), (6, 7)), ((5, 8), (4, 8)), ((5, 8), (5, 7))] wking2moves = [((5, 4), (6, 4)), ((5, 4), (6, 3)), ((5, 4), (4, 4)), ((5, 4), (4, 5)), ((5, 4), (5, 5)), ((5, 4), (5, 3)), ((5, 4), (6, 5)), ((5, 4), (4, 3))] self.assertTrue( set( self.logic.getValidKingMoves(wking.getpos().getPosAsPair(), self.board)) == set(wkingmoves)) self.assertTrue( set( self.logic.getValidKingMoves(bking.getpos().getPosAsPair(), self.board)) == set(bkingmoves)) self.assertTrue( set( self.logic.getValidKingMoves(wking2.getpos().getPosAsPair(), self.board)) == set(wking2moves))
def test_move(self): wking = Chess.Piece(1, "E", True, Chess.PieceType.king, True) bking = Chess.Piece(8, "E", True, Chess.PieceType.king, False) self.board.addpiece(wking) self.board.addpiece(bking) self.logic.move(wking, (6, 1), self.board) self.assertTrue(self.board.getpos(6, 1) is wking) self.assertTrue( self.board.getpos(5, 1).gettype() == Chess.PieceType.empty) self.assertTrue(wking.getpos().getPosAsPair() == (6, 1))
def test_getAnyMoves(self): wking = Chess.Piece(1, "E", True, Chess.PieceType.king, True) bking = Chess.Piece(8, "E", True, Chess.PieceType.king, False) wrook1 = Chess.Piece(8, "A", True, Chess.PieceType.rook, True) wrook2 = Chess.Piece(7, "B", True, Chess.PieceType.rook, True) self.board.addpiece(wking) self.board.addpiece(bking) self.board.addpiece(wrook1) self.board.addpiece(wrook2) self.assertFalse(self.logic.getAnyMoves(False, self.board)) self.assertTrue(self.logic.getAnyMoves(True, self.board))
def test_checkState(self): wking = Chess.Piece(1, "E", True, Chess.PieceType.king, True) bking = Chess.Piece(8, "E", True, Chess.PieceType.king, False) brook = Chess.Piece(3, "E", True, Chess.PieceType.rook, False) bqueen = Chess.Piece(2, "E", True, Chess.PieceType.queen, False) wrook = Chess.Piece(6, "E", True, Chess.PieceType.rook, True) wqueen = Chess.Piece(7, "E", True, Chess.PieceType.queen, True) wqueen2 = Chess.Piece(6, "E", True, Chess.PieceType.queen, True) wbishop = Chess.Piece(7, "E", True, Chess.PieceType.bishop, True) bqueen2 = Chess.Piece(3, "E", True, Chess.PieceType.queen, False) bbishop = Chess.Piece(2, "E", True, Chess.PieceType.bishop, False) self.board.addpieces(wking, bking) self.assertTrue( self.logic.checkState(self.board, True) == Chess.ChessState.inProgress) self.board.setEmptyBoard() self.board.addpieces(wking, bking, bqueen) self.assertTrue( self.logic.checkState(self.board, True) == Chess.ChessState.whiteChecked) self.board.setEmptyBoard() self.board.addpieces(wking, bking, brook) self.assertTrue( self.logic.checkState(self.board, True) == Chess.ChessState.whiteChecked) self.board.setEmptyBoard() self.board.addpieces(wking, bking, brook, bqueen) self.assertTrue( self.logic.checkState(self.board, True) == Chess.ChessState.whiteCheckmated) self.board.setEmptyBoard() self.board.addpieces(wking, bking, wqueen) self.assertTrue( self.logic.checkState(self.board, False) == Chess.ChessState.blackChecked) self.board.setEmptyBoard() self.board.addpieces(wking, bking, wrook) self.assertTrue( self.logic.checkState(self.board, False) == Chess.ChessState.blackChecked) self.board.setEmptyBoard() self.board.addpieces(wking, bking, wrook, wqueen) self.assertTrue( self.logic.checkState(self.board, False) == Chess.ChessState.blackCheckmated) self.board.setEmptyBoard() self.board.addpieces(wking, bking, wbishop, wqueen2) self.assertTrue( self.logic.checkState(self.board, False) == Chess.ChessState.draw) self.board.setEmptyBoard() self.board.addpieces(wking, bking, bbishop, bqueen2) self.assertTrue( self.logic.checkState(self.board, True) == Chess.ChessState.draw)
def test_getValidKnightMoves(self): wking = Chess.Piece(1, "E", True, Chess.PieceType.king, True) bking = Chess.Piece(8, "E", True, Chess.PieceType.king, False) bknight = Chess.Piece(6, "D", True, Chess.PieceType.knight, False) self.board.addpieces(wking, bking, bknight) bknightmoves = [((4, 6), (6, 7)), ((4, 6), (6, 5)), ((4, 6), (5, 4)), ((4, 6), (2, 5)), ((4, 6), (2, 7)), ((4, 6), (3, 4)), ((4, 6), (3, 8))] self.assertTrue( set( self.logic.getValidKnightMoves(bknight.getpos().getPosAsPair( ), self.board)) == set(bknightmoves))
def test_validateMove(self): wking = Chess.Piece(1, "E", True, Chess.PieceType.king, True) bking = Chess.Piece(8, "E", True, Chess.PieceType.king, False) wrook = Chess.Piece(3, "C", True, Chess.PieceType.rook, True) wbishop = Chess.Piece(3, "G", True, Chess.PieceType.bishop, True) wrook2 = Chess.Piece(3, "E", True, Chess.PieceType.rook, True) bqueen = Chess.Piece(7, "E", True, Chess.PieceType.queen, False) bbishop = Chess.Piece(4, "H", True, Chess.PieceType.bishop, False) bbishop2 = Chess.Piece(5, "A", True, Chess.PieceType.bishop, False) self.board.addpieces(wking, bking, wrook, wbishop, wrook, wrook2) self.assertTrue(self.logic.validateMove((5, 3), (5, 4), self.board)) self.assertTrue(self.logic.validateMove((5, 1), (4, 2), self.board)) self.assertTrue(self.logic.validateMove((5, 8), (6, 7), self.board)) self.assertTrue(self.logic.validateMove((3, 3), (3, 8), self.board)) self.assertTrue(self.logic.validateMove((7, 3), (2, 8), self.board)) self.board.addpieces(bqueen, bbishop, bbishop2) self.assertTrue(self.logic.validateMove((5, 3), (5, 4), self.board)) self.assertFalse(self.logic.validateMove((5, 3), (4, 3), self.board)) self.assertTrue(self.logic.validateMove((5, 1), (4, 2), self.board)) self.assertTrue(self.logic.validateMove((5, 8), (6, 7), self.board)) self.assertFalse(self.logic.validateMove((3, 3), (3, 8), self.board)) self.assertFalse(self.logic.validateMove((7, 3), (2, 8), self.board)) self.assertTrue( self.logic.validateMove((7, 3), (2, 8), self.board, False)) self.assertTrue(self.logic.validateMove((7, 3), (8, 4), self.board))
def test_getValidPawnMoves(self): wking = Chess.Piece(1, "E", True, Chess.PieceType.king, True) bking = Chess.Piece(8, "E", True, Chess.PieceType.king, False) wpawn = Chess.Piece(7, "H", True, Chess.PieceType.pawn, True) bpawn = Chess.Piece(4, "G", True, Chess.PieceType.pawn, False) wpawn2 = Chess.Piece(3, "H", True, Chess.PieceType.pawn, True) bpawn2 = Chess.Piece(3, "F", True, Chess.PieceType.pawn, False) wpawn3 = Chess.Piece(3, "E", True, Chess.PieceType.pawn, True) wpawn4 = Chess.Piece(2, "A", True, Chess.PieceType.pawn, True) wpawn5 = Chess.Piece(2, "B", True, Chess.PieceType.pawn, True) bpawn3 = Chess.Piece(4, "C", True, Chess.PieceType.pawn, False) wpawn3.setEnPassant(True) self.board.addpieces(wking, bking, wpawn, wpawn2, wpawn3, wpawn4, wpawn5, bpawn, bpawn2, bpawn3) self.assertTrue( self.logic.getValidPawnMoves(wpawn.getpos().getPosAsPair(), self.board) == [((8, 7), (8, 8))]) self.assertTrue( self.logic.getValidPawnMoves(bpawn.getpos().getPosAsPair(), self.board) == [((7, 4), (7, 3)), ((7, 4), (8, 3))]) self.assertTrue( self.logic.getValidPawnMoves(wpawn2.getpos().getPosAsPair(), self.board) == [((8, 3), (8, 4)), ((8, 3), (7, 4))]) self.assertTrue( self.logic.getValidPawnMoves(wpawn3.getpos().getPosAsPair(), self.board) == [((5, 3), (5, 4))]) self.assertTrue( self.logic.getValidPawnMoves( bpawn2.getpos().getPosAsPair(), self.board) == [((6, 3), ( 6, 2)), ((6, 3), (5, 2, Chess.SpecialMove.en_passant))]) self.assertTrue( self.logic.getValidPawnMoves(wpawn4.getpos().getPosAsPair(), self.board) == [((1, 2), (1, 3)), ((1, 2), (1, 4))]) self.assertTrue( self.logic.getValidPawnMoves( wpawn5.getpos().getPosAsPair(), self.board) == [((2, 2), ( 2, 3)), ((2, 2), (2, 4, Chess.SpecialMove.en_passant_trigger))])
def dropped(self, p): """ This means that someone dropped the dragged thing on (x,y). """ x,y = p if self.board.win is not None: return x //= self.field_width y //= self.field_height if self.dragged_piece is not None and ((self.dragged_piece.position, (x, y)) in self.possible_moves \ or ( self.dragged_piece.position, (x, y), "Queen") in self.possible_moves): self.board.make_move(self.dragged_piece.position, (x, y)) print(str(self.dragged_piece.position) + " " + str((x, y))) print(self.board) self.pieces = [] index = 0 for field in self.board.table: if field is not None: self.pieces.append(Piece(field, Chess.convert_index(index))) index += 1 self.board.recalculate_moves() self.dragged_piece.dragged = False self.dragged_piece = None self.possible_moves = [] elif self.dragged_piece is not None: self.dragged_piece.dragged = False self.dragged_piece = None
def test_move_side_effects(self): wking = Chess.Piece(1, "E", True, Chess.PieceType.king, True) bking = Chess.Piece(8, "E", True, Chess.PieceType.king, False) wpawn = Chess.Piece(7, "H", True, Chess.PieceType.pawn, True) bpawn = Chess.Piece(4, "H", True, Chess.PieceType.pawn, False) bpawn.setEnPassant(True) self.board.addpiece(wking) self.board.addpiece(bking) self.board.addpiece(wpawn) self.board.addpiece(bpawn) self.logic.move_side_effects(wpawn, (8, 8), self.board) self.assertTrue(wpawn.gettype() == Chess.PieceType.queen) self.assertFalse(bpawn.getEnPassant()) self.logic.move_side_effects(wking, (6, 1), self.board) self.assertFalse(wking.getHasNotMoved()) self.assertTrue(bking.getHasNotMoved())
def __init__(self): self.round = 1 self.p1 = Player(100) self.p2 = Player(100) self.board = Chess.Board() self.winner = None self.finished = False self.fight_time = 30 self.chess_time = 60
def test_getValidBishopMoves(self): wking = Chess.Piece(1, "H", True, Chess.PieceType.king, True) bking = Chess.Piece(7, "H", True, Chess.PieceType.king, False) wbishop = Chess.Piece(4, "E", True, Chess.PieceType.bishop, True) wpawn = Chess.Piece(2, "C", True, Chess.PieceType.pawn, True) bpawn = Chess.Piece(6, "C", True, Chess.PieceType.pawn, False) self.board.addpieces(wking, bking, wbishop, wpawn, bpawn) wbishopmoves = [((5, 4), (6, 5)), ((5, 4), (7, 6)), ((5, 4), (8, 7)), ((5, 4), (4, 3)), ((5, 4), (4, 5)), ((5, 4), (3, 6)), ((5, 4), (6, 3)), ((5, 4), (7, 2))] val = self.logic.getValidBishopMoves(wbishop.getpos().getPosAsPair(), self.board) self.assertTrue( set( self.logic.getValidBishopMoves(wbishop.getpos().getPosAsPair( ), self.board)) == set(wbishopmoves))
def test_getValidRookMoves(self): wking = Chess.Piece(1, "E", True, Chess.PieceType.king, True) bking = Chess.Piece(8, "E", True, Chess.PieceType.king, False) brook = Chess.Piece(4, "E", True, Chess.PieceType.rook, False) wpawn = Chess.Piece(4, "B", True, Chess.PieceType.pawn, True) bpawn = Chess.Piece(4, "G", True, Chess.PieceType.pawn, False) self.board.addpieces(wking, bking, brook, wpawn, bpawn) brookmoves = [((5, 4), (4, 4)), ((5, 4), (3, 4)), ((5, 4), (2, 4)), ((5, 4), (6, 4)), ((5, 4), (5, 3)), ((5, 4), (5, 2)), ((5, 4), (5, 1)), ((5, 4), (5, 5)), ((5, 4), (5, 6)), ((5, 4), (5, 7))] val = self.logic.getValidRookMoves(brook.getpos().getPosAsPair(), self.board) self.assertTrue( set( self.logic.getValidRookMoves(brook.getpos().getPosAsPair(), self.board)) == set(brookmoves))
def onOpen(board): File = filedialog.askopenfilename(initialdir="/home", title="Open file", filetypes=(("main files", "*txt*"), ("All files", "*.*"))) clear_board(board) input_file = open(File, 'r') input_data = input_file.readlines() input_file.closed for i in input_data: Piece, Colour, Row, Column = i.rstrip().split(' ') print(Piece, Colour, Row, Column) add_piece( board, eval(Piece + '(' + 'str(Colour)' + ', ' + 'int(Row)' + ', ' + 'int(Column)' + ')')) window = Chess.set_up_window() Chess.layout_board(window, board) window.mainloop()
def MoveSearch(temp_board, pos, direction,cur_player,number): # if pos.x<0 or pos.y<0 or pos.x>7 or pos.y>7: # 位置超出棋盘 x=-1 y=-1 # Position = Chess.Position(-1, -1) Num=0 if direction==1: x=pos.x-1 y=pos.y-1 elif direction==2: x=pos.x y=pos.y-1 elif direction==3: x=pos.x+1 y=pos.y-1 elif direction==4: x=pos.x-1 y=pos.y elif direction==5: x=pos.x+1 y=pos.y elif direction==6: x=pos.x-1 y=pos.y+1 elif direction==7: x=pos.x y=pos.y+1 elif direction==8: x=pos.x+1 y=pos.y+1 # print("MoveSearch Position:" + str(x) + " " + str(y)) if x < 0 or x > 7 or y < 0 or y > 7: # 该方向超出棋盘 return Num # 没有可行位置 if temp_board[x][y] == 0: # 该方向没有棋子 return Num # 没有可行位置 if temp_board[x][y] == -cur_player: # 该方向有对手的棋子 Num = MoveSearch(temp_board, Chess.Position(x, y), direction, cur_player, number + 1) if temp_board[x][y] == cur_player: # 找到终点的己方棋子 if number == 0 and Num==0: # 中间没有棋子 return Num # 没有可行位置 else: # print("game MoveSearch pos:("+str(pos.x)+","+str(pos.y)+")") temp_board[pos.x][pos.y] = cur_player # 翻转棋子 if Num<number: Num=number return Num # 找到当前可行位置 else: Num=0 return Num
def test_getValidQueenMoves(self): wking = Chess.Piece(1, "H", True, Chess.PieceType.king, True) bking = Chess.Piece(7, "H", True, Chess.PieceType.king, False) wqueen = Chess.Piece(4, "E", True, Chess.PieceType.queen, True) wpawn = Chess.Piece(2, "C", True, Chess.PieceType.pawn, True) bpawn = Chess.Piece(6, "C", True, Chess.PieceType.pawn, False) self.board.addpieces(wking, bking, wqueen, wpawn, bpawn) wqueenmoves = [((5, 4), (6, 5)), ((5, 4), (7, 6)), ((5, 4), (8, 7)), ((5, 4), (4, 3)), ((5, 4), (4, 5)), ((5, 4), (3, 6)), ((5, 4), (6, 3)), ((5, 4), (7, 2)), ((5, 4), (4, 4)), ((5, 4), (3, 4)), ((5, 4), (2, 4)), ((5, 4), (1, 4)), ((5, 4), (6, 4)), ((5, 4), (7, 4)), ((5, 4), (8, 4)), ((5, 4), (5, 3)), ((5, 4), (5, 2)), ((5, 4), (5, 1)), ((5, 4), (5, 5)), ((5, 4), (5, 6)), ((5, 4), (5, 7)), ((5, 4), (5, 8))] self.assertTrue( set( self.logic.getValidQueenMoves(wqueen.getpos().getPosAsPair(), self.board)) == set(wqueenmoves))
def main(): pygame.init() screen = pygame.display.set_mode((900, 600)) pygame.display.set_caption('历史记录') chess = Chess.Chess(screen) tkinter.Tk().withdraw() gameList = chess.getGameList() gameSum = len(gameList) maxPage = gameSum // 10 + 1 if gameSum % 10 else gameSum // 10 page = 1 if maxPage == 0: messagebox.showinfo('提示', '当前没有历史记录') return recordCnt = showInfo(screen, gameList, page, gameSum) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.MOUSEBUTTONUP: #turn to previous page if Utility.isInRect(event.pos, (100, 485, 310, 555)): if page == 1: messagebox.showinfo('提示', '没有上一页了') else: page -= 1 recordCnt = showInfo(screen, gameList, page, gameSum) #turn to next page elif Utility.isInRect(event.pos, (370, 485, 580, 555)): if page == maxPage: messagebox.showinfo('提示', '没有下一页了') else: page += 1 recordCnt = showInfo(screen, gameList, page, gameSum) #return to main menu elif Utility.isInRect(event.pos, (660, 485, 800, 555)): return #choose a specific game record elif Utility.isInRect(event.pos, (125, 70, 790, 70 + recordCnt * 40)): num = (event.pos[1] - 70) // 40 reviewGame(chess, gameList[(page - 1) * 10 + num][0]) showInfo(screen, gameList, page, gameSum) pygame.display.update()
def Judge(posx, posy, board, root, step): maxium = 0 print("-----Judge-------") node = root for i in range(step): node = node.children[0] index = -1 for j in node.children: index = index + 1 if j.position == Chess.Position(posy, posx): return index index = -1 return index
def __init__(self): super().__init__() self.setWindowIcon(QIcon('Chess-Game-grey.ico')) self.setWindowTitle('Chess') self.setMinimumSize(640, 400) self.resize(640, 400) # Center window window = self.frameGeometry() window.moveCenter(QDesktopWidget().availableGeometry().center()) self.move(window.topLeft()) self.game = Chess.Game() self.initUI()
def menu(window, board): menubar = tkinter.Menu(window) filemenu = tkinter.Menu(menubar, tearoff=0) editmenu = tkinter.Menu(menubar, tearoff=0) viewmenu = tkinter.Menu(menubar, tearoff=0) toolmenu = tkinter.Menu(menubar, tearoff=0) helpmenu = tkinter.Menu(menubar, tearoff=0) filemenu.add_command(label="New", command=lambda: Chess.play_chess('File.py')) filemenu.add_command(label="Open", command=lambda: onOpen(board)) filemenu.add_command(label="Save", command=lambda: onSave(board)) filemenu.add_separator() filemenu.add_command(label="Exit", command=lambda: window.destroy()) editmenu.add_command(label="custormise pieces", command=lambda: openGuide()) editmenu.add_command(label="custormise board", command=lambda: openGuide()) editmenu.add_checkbutton(label='Blindfold Chess', command=lambda: openGuide()) viewmenu.add_checkbutton(label='points', command=lambda: openGuide()) viewmenu.add_checkbutton(label='pieces taken', command=lambda: openGuide()) viewmenu.add_checkbutton(label='computer evaluation', command=lambda: openGuide()) viewmenu.add_command(label="game history", command=lambda: openGuide()) toolmenu.add_command(label="takeback", command=lambda: openGuide()) toolmenu.add_command(label="flip board", command=lambda: openGuide()) toolmenu.add_command(label="Request stalemate", command=lambda: openGuide()) toolmenu.add_command(label="Resighn", command=lambda: openGuide()) toolmenu.add_command(label="hint", command=lambda: openGuide()) helpmenu.add_command(label="Open Guide", command=lambda: openGuide()) menubar.add_cascade(label="File", menu=filemenu) menubar.add_cascade(label="Edit", menu=editmenu) menubar.add_cascade(label="View", menu=viewmenu) menubar.add_cascade(label="Tools", menu=toolmenu) menubar.add_cascade(label="Help", menu=helpmenu) window.config(menu=menubar)
def __init__(self): """ Initialize images and create beginning board. Also recalculate the moves that can be done on the board. """ self.field_width = 60 self.field_height = 60 self.width = self.field_width * 8 self.height = self.field_height * 8 self.board = Chess.Board() self.board.recalculate_moves() # Change to prettier fields self.white_field = pygame.Surface((self.field_width, self.field_height)) self.white_field.fill((245, 222, 179)) # Change to prettier fields. self.black_field = pygame.Surface((self.field_width, self.field_height)) self.black_field.fill((205, 133, 63)) self.move_field = pygame.Surface((self.field_width, self.field_height)) self.move_field.fill((139, 0, 0)) self.move_field.set_alpha(115) self.pieces = [] index = 0 for field in self.board.table: if field is not None: self.pieces.append(Piece(field, Chess.convert_index(index))) index += 1 self.dragged_piece = None self.possible_moves = [] self.opaque = 0 self.white_wins = pygame.image.load("res/white_wins.png") self.black_wins = pygame.image.load("res/black_wins.png")
def display(self, screen): """ Display current status of the board. :param screen: Screen on which the board is to be displayed. """ for i in range(64): (x, y) = Chess.convert_index(i) if (x + y) % 2 == 0: screen.blit(self.white_field, (x * self.field_width, y * self.field_height)) else: screen.blit(self.black_field, (x * self.field_width, y * self.field_height)) for move in self.possible_moves: if len(move) == 2: (previous, next) = move screen.blit(self.move_field, (previous[0] * self.field_width, previous[1] * self.field_height)) screen.blit(self.move_field, (next[0] * self.field_width, next[1] * self.field_height)) else: (previous, next, promotion) = move screen.blit(self.move_field, (previous[0] * self.field_width, previous[1] * self.field_height)) screen.blit(self.move_field, (next[0] * self.field_width, next[1] * self.field_height)) for piece in self.pieces: piece.display(screen) if self.board.win is not None: self.opaque += 3 if self.opaque > 225: self.opaque = 225 surface = pygame.Surface((self.width, self.height)) if self.board.win == "White": surface.fill((255, 255, 255)) else: surface.fill((0, 0, 0)) surface.set_alpha(self.opaque) screen.blit(surface, (0, 0)) if self.board.win == "White": screen.blit(self.white_wins, (0, 0)) else: screen.blit(self.black_wins, (0, 0))
def test_sim_move(self): wking = Chess.Piece(1, "E", True, Chess.PieceType.king, True) bking = Chess.Piece(8, "E", True, Chess.PieceType.king, False) wrook = Chess.Piece(1, "A", True, Chess.PieceType.rook, True) brook = Chess.Piece(8, "H", True, Chess.PieceType.rook, False) wpawn = Chess.Piece(5, "G", True, Chess.PieceType.pawn, True) bpawn = Chess.Piece(5, "H", True, Chess.PieceType.pawn, False) bpawn2 = Chess.Piece(7, "F", True, Chess.PieceType.pawn, False) self.board.addpieces(wking, bking, wrook, brook, wpawn, bpawn, bpawn2) newboard = self.logic.sim_move( (5, 1), (3, 1, Chess.SpecialMove.queen_castle), self.board) self.assertTrue( newboard.getpos(3, 1).gettype() == Chess.PieceType.king) self.assertTrue( newboard.getpos(4, 1).gettype() == Chess.PieceType.rook) newboard = self.logic.sim_move( (5, 8), (7, 8, Chess.SpecialMove.king_castle), self.board) self.assertTrue( newboard.getpos(7, 8).gettype() == Chess.PieceType.king) self.assertTrue( newboard.getpos(6, 8).gettype() == Chess.PieceType.rook) newboard = self.logic.sim_move( (7, 5), (8, 6, Chess.SpecialMove.en_passant), self.board) self.assertTrue( newboard.getpos(8, 6).gettype() == Chess.PieceType.pawn) self.assertTrue( newboard.getpos(8, 5).gettype() == Chess.PieceType.empty) newboard = self.logic.sim_move( (8, 5), (7, 4, Chess.SpecialMove.en_passant), self.board) self.assertTrue( newboard.getpos(7, 4).gettype() == Chess.PieceType.pawn) self.assertTrue( newboard.getpos(7, 5).gettype() == Chess.PieceType.empty) newboard = self.logic.sim_move( (6, 7), (6, 5, Chess.SpecialMove.en_passant_trigger), self.board) self.assertTrue(newboard.getpos(6, 5).getEnPassant())
#Test case for chess move validation import Chess board = [['WR', "WH", "WB", "WQ", "WK", "WB", "WH", "WR"], ['WP', "WP", "WP", "WP", "WP", "WP", "WP", "WP"], ["--", "--", "--", "--", "--", "--", "--", "--"], ["--", "--", "--", "--", "--", "--", "--", "--"], ["--", "--", "BP", "--", "--", "--", "--", "--"], ["--", "--", "--", "--", "--", "--", "--", "--"], ['BP', "BP", "--", "BP", "BP", "BP", "BP", "BP"], ['BR', "BH", "BB", "BQ", "BK", "BB", "BH", "BR"]] chess = Chess.Chess() chess.setBoardPosition(board) #case 1 print("\n\tBP", "63", "43\n") chess.makeMove("BP", "63", "43") #valid print("\n\tBP", "64", "45\n") chess.makeMove("BP", "64", "45") #invalid print("\n\tBP", "65", "46\n") chess.makeMove("BP", "65", "46") #invalid print("\n\tBP", "66", "55\n") chess.makeMove("BP", "66", "55") #invalid print("\n\tBP", "66", "65\n") chess.makeMove("BP", "66", "65") #invalid print("\n\tBP", "42", "52\n") chess.makeMove("BP", "42", "52") #invalid9 #case 2 Black Pawn 1-step
def main(): pygame.init() screen=pygame.display.set_mode((900,600)) pygame.display.set_caption('单机对战') chess=Chess.Chess(screen) chess.drawBackground() chess.drawBoard() font=pygame.font.Font(os.getcwd()+'\source\\font\华文行楷.ttf',50) returnText=font.render('返回',True,pygame.Color('black')) screen.blit(returnText,(700,523)) undoText=font.render('悔棋',True,pygame.Color('black')) screen.blit(undoText,(700,453)) defeatText=font.render('认输',True,pygame.Color('black')) screen.blit(defeatText,(700,383)) chess.drawPlayer(1) pygame.display.update() #use player to control which side is going to drop pieces #1 means black side. 2 means white side. the same as Chess.py player=1 while True: for event in pygame.event.get(): if event.type==pygame.QUIT: sys.exit() elif event.type==pygame.MOUSEBUTTONUP: #drop a piece if chess.isInBoard(event.pos): pos=chess.findPosInBoard(event.pos) if chess.board[pos[0]][pos[1]]!=0: continue chess.dropPiece(pos,player) if chess.isWinner(pos): chess.drawWinner(player) chess.recordGame('单机对战','黑白同机','黑方胜' if player==1 else '白方胜') time.sleep(1) return player=3-player chess.drawPlayer(player) #return to main menu elif Utility.isInRect(event.pos,(700,523,800,573)): return #undo a drop elif Utility.isInRect(event.pos,(700,453,800,503)): chess.undoDrop() player=3-player chess.drawPlayer(player) #one side give up elif Utility.isInRect(event.pos,(700,383,800,433)): chess.drawWinner(3-player) chess.recordGame('单机对战','黑白同机','黑方胜' if 3-player==1 else '白方胜') time.sleep(1) return pygame.display.update()
#! Python 3.7 with usage of Tkinter and PIL for complete usage of the application # Creator : Sean Morgan # Site : github.com/Firesean import Chess as Chs import Interface as Ui game = Ui.Interface(Chs.Chess(), 650)
LastTimeWhite = 0.0 pygame.init() screen = pygame.display.set_mode((canvas_w, canvas_h)) pygame.display.set_caption("翻转棋") FPS = 30 clock = pygame.time.Clock() # 加载背景图片 base_folder = os.path.dirname(__file__) bg_img = pygame.image.load(os.path.join(base_folder, "boardBG.jpg")).convert() board = game.Init(ChessBoard) root = Chess.Node() # root就是棋盘初始的样子,判定条件为没有parents root = game.PossibleMove(board, root, cur_player) root.Board = board while True: drawChessBoard(screen) pygame.display.update() clock.tick(FPS) if StartFlag == 1: if game.isTerminal(board, cur_player) == True: cur_player = 2 if cur_player == 1: print("black") if isTurn(root, cur_player, step) == False: cur_player = -1 temp_board = copy.deepcopy(board)
def start(self, rows, columns): root = Tk() game_gui = Chess.Chess(root) root.mainloop()
def main(): pygame.init() screen = pygame.display.set_mode((900, 600)) pygame.display.set_caption('联机对战') screen.fill(pygame.Color('white')) Utility.showText(screen, (150, 270), 60, 'black', '请使用控制台进行联机') chess = Chess.Chess(screen) tkinter.Tk().withdraw() #record player's name myName = input('请输入您的游戏昵称:') #use UDP to communicate. port:8001 myAddress = (socket.gethostname(), 8001) mySocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) mySocket.bind(myAddress) #choose to be the server or the client #1 represents the client(black side), and 2 represents the server(white side) print('\n请输入数字选择您的联机方式:') print('1.填入对方的IP地址主动联机') print('2.等待他人连接到本设备') choice = int(input('您的选择是:')) ''' oppe is short for opposite in this file msg is short for message in this file exchange initial info in this part ''' if choice == 1: oppoAddress = (input('请输入对方的IP地址(对方此时必须处于等待状态):'), 8001) mySocket.sendto(myName.encode(), oppoAddress) print('\n正在联机...') recvMsg = mySocket.recvfrom(1024) oppoName = recvMsg[0].decode() else: print('\n请等待他人的联机...') recvMsg = mySocket.recvfrom(1024) oppoAddress = recvMsg[1] oppoName = recvMsg[0].decode() mySocket.sendto(myName.encode(), oppoAddress) #perform initialization print('游戏开始!') chess.drawBackground() chess.drawBoard() font = pygame.font.Font(os.getcwd() + '\source\\font\华文行楷.ttf', 50) returnText = font.render('返回', True, pygame.Color('black')) screen.blit(returnText, (700, 523)) undoText = font.render('悔棋', True, pygame.Color('black')) screen.blit(undoText, (700, 453)) defeatText = font.render('认输', True, pygame.Color('black')) screen.blit(defeatText, (700, 383)) #choice has the same value as player if choice == 1: chess.drawPlayer(1, myName) else: chess.drawPlayer(1, oppoName) ''' start the game, and here're some msg instructions msg content(str): exit:it means the opponent exits the game win:it means the opponent chooses to give up undo:it means the opponent undoes a drop(only in your turn can you undo drops) admit:it means you admit the undoing request of the opponent reject:it means you reject the undoing request of the opponent x,y:it means the opponent drop a piece at (x,y) ''' while True: #the server receives msg here if choice == 2: while True: recvMsg = mySocket.recvfrom(1024) recvStr = recvMsg[0].decode() if recvStr == 'exit': screen.fill(pygame.Color('white')) Utility.showText(screen, (240, 270), 60, 'black', '对方离开了游戏') mySocket.close() time.sleep(1) return elif recvStr == 'win': messagebox.showinfo('提示', '对方选择认输') chess.drawWinner(choice, myName) chess.recordGame('联机对战', '我方执白', '白方胜') mySocket.close() time.sleep(1) return elif recvStr == 'undo': admitUndo = messagebox.askyesno('提示', '对方请求悔棋,是否同意?') if admitUndo: mySocket.sendto('admit'.encode(), oppoAddress) chess.undoDrop() chess.undoDrop() else: mySocket.sendto('reject'.encode(), oppoAddress) continue else: x, y = map(int, recvStr.split(',')) chess.dropPiece((x, y), 3 - choice) if chess.isWinner((x, y)): chess.drawWinner(3 - choice, oppoName) chess.recordGame('联机对战', '我方执白', '黑方胜') mySocket.close() time.sleep(1) return chess.drawPlayer(choice, myName) break #use while loop to assure the player(server or client) doing an efficient operation alreadyDrop = False while True: #use for loop to deal with events for event in pygame.event.get(): if event.type == pygame.QUIT: mySocket.sendto('exit'.encode(), oppoAddress) mySocket.close() sys.exit() elif event.type == pygame.MOUSEBUTTONUP: #drop a piece if chess.isInBoard(event.pos): pos = chess.findPosInBoard(event.pos) if chess.board[pos[0]][pos[1]] != 0: continue chess.dropPiece(pos, choice) mySocket.sendto( str(pos).strip('()').encode(), oppoAddress) if chess.isWinner(pos): chess.drawWinner(choice, myName) if choice == 1: chess.recordGame('联机对战', '我方执黑', '黑方胜') else: chess.recordGame('联机对战', '我方执白', '白方胜') mySocket.close() time.sleep(1) return chess.drawPlayer(3 - choice, oppoName) alreadyDrop = True break #return to main menu elif Utility.isInRect(event.pos, (700, 523, 800, 573)): mySocket.sendto('exit'.encode(), oppoAddress) mySocket.close() return #undo a drop elif Utility.isInRect(event.pos, (700, 453, 800, 503)): mySocket.sendto('undo'.encode(), oppoAddress) recvMsg = mySocket.recvfrom(1024) recvStr = recvMsg[0].decode() if recvStr == 'admit': chess.undoDrop() chess.undoDrop() continue #give up the game elif Utility.isInRect(event.pos, (700, 383, 800, 433)): mySocket.sendto('win'.encode(), oppoAddress) chess.drawWinner(3 - choice, oppoName) if choice == 1: chess.recordGame('联机对战', '我方执黑', '白方胜') else: chess.recordGame('联机对战', '我方执白', '黑方胜') mySocket.close() time.sleep(1) return #break the while loop if alreadyDrop: break #the client receives msg here if choice == 1: while True: recvMsg = mySocket.recvfrom(1024) recvStr = recvMsg[0].decode() if recvStr == 'exit': screen.fill(pygame.Color('white')) Utility.showText(screen, (240, 270), 60, 'black', '对方离开了游戏') mySocket.close() time.sleep(1) return elif recvStr == 'win': messagebox.showinfo('提示', '对方选择认输') chess.drawWinner(choice, myName) chess.recordGame('联机对战', '我方执黑', '黑方胜') mySocket.close() time.sleep(1) return elif recvStr == 'undo': admitUndo = messagebox.askyesno('提示', '对方请求悔棋,是否同意?') if admitUndo: mySocket.sendto('admit'.encode(), oppoAddress) chess.undoDrop() chess.undoDrop() else: mySocket.sendto('reject'.encode(), oppoAddress) continue else: x, y = map(int, recvStr.split(',')) chess.dropPiece((x, y), 3 - choice) if chess.isWinner((x, y)): chess.drawWinner(3 - choice, oppoName) chess.recordGame('联机对战', '我方执黑', '白方胜') mySocket.close() time.sleep(1) return chess.drawPlayer(choice, myName) break pygame.display.update()
def main(): pygame.init() screen=pygame.display.set_mode((900,600)) pygame.display.set_caption('人机对战') chess=Chess.Chess(screen) chess.drawBackground() chess.drawBoard() Utility.showText(screen,(700,523),50,'blue','返回') Utility.showText(screen,(700,453),50,'blue','悔棋') pygame.display.update() tkinter.Tk().withdraw() isBlack=messagebox.askyesno('询问','是否要执黑棋先行') chess.openAI() while True: if not isBlack: pos=chess.askAIForPos() chess.dropPiece(pos,1) if chess.isWinner(pos): chess.drawWinner(1) chess.recordGame('人机对战','我方执白','黑方胜') time.sleep(1) return alreadyDrop=False while True: for event in pygame.event.get(): if event.type==pygame.QUIT: sys.exit() elif event.type==pygame.MOUSEBUTTONUP: #return to main menu if Utility.isInRect(event.pos,(700,523,800,573)): return #undo a drop elif Utility.isInRect(event.pos,(700,453,800,503)): chess.undoDrop() chess.undoDrop() #drop a piece elif chess.isInBoard(event.pos): pos=chess.findPosInBoard(event.pos) if chess.board[pos[0]][pos[1]]!=0: continue chess.dropPiece(pos,1 if isBlack else 2) if chess.isWinner(pos): if isBlack: chess.drawWinner(1) chess.recordGame('人机对战','我方执黑','黑方胜') else: chess.drawWinner(2) chess.recordGame('人机对战','我方执白','白方胜') time.sleep(1) return alreadyDrop=True break pygame.display.update() if alreadyDrop: break if isBlack: pos=chess.askAIForPos() chess.dropPiece(pos,2) if chess.isWinner(pos): chess.drawWinner(2) chess.recordGame('人机对战','我方执黑','白方胜') time.sleep(1) return
def setUp(self): self.board = Chess.ChessBoard() self.logic = Chess.ChessLogic() self.board.setEmptyBoard()