def init_chessList(): for i in range(8): Board.chessList.append(0) for i in range(8, 15): chessObj = Chess(i) Board.chessList.append(chessObj) Board.chessList.append(0) for i in range(16, 23): chessObj = Chess(i) Board.chessList.append(chessObj)
def __init__(self): super(MainWindow, self).__init__() self.scene = QGraphicsScene(self) self.game = Chess() self.scene.addItem(self.game) self.scene.setSceneRect(0, 0, 360, 360) view = QGraphicsView(self.scene, self) layout = QGridLayout() # info_window = QLineEdit() # info_window.setFocusPolicy(Qt.NoFocus) btn_new_game = QPushButton("new game", self) btn_new_game.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.MinimumExpanding) btn_new_game.clicked.connect(self.button_actions) btn_new_game.setFocusPolicy(Qt.NoFocus) btn_exit = QPushButton("exit", self) btn_exit.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.MinimumExpanding) btn_exit.clicked.connect(self.button_actions) btn_exit.setFocusPolicy(Qt.NoFocus) layout.addWidget(view, 0, 0, 8, 8) layout.addWidget(btn_new_game, 8, 0, 1, 8) layout.addWidget(btn_exit, 9, 0, 1, 8) self.setLayout(layout) self.setGeometry(300, 300, 390, 450) self.setCacheMode(QGraphicsView.CacheBackground) self.setWindowTitle("Chess")
def __init__(self): self.chess = Chess() self.is_game_running = False self.get_view('MAIN_MENU')
def __init__(self): self.app = QtWidgets.QApplication([]) self.dlg = QtWidgets.QDialog() vbl = QtWidgets.QVBoxLayout(self.dlg) self.chess = Chess(self.callback) vbl.addWidget(self.chess) self.dlg.show()
def from_initial(): # Returns a chess object with pieces at their initial positions history_stack = History() board = Board(history_stack) for piece_cls, player, square in INITIAL_POSITIONS: board.add(piece_cls(player, board), square) return Chess(board, Player.WHITE, history_stack)
def __init__(self): """ Virtually private constructor. """ if Singleton._chess is not None: raise Exception("This class is a singleton!") else: Singleton._chess = Chess()
def log(): root = Tk() root.title('17074304') root.geometry('600x450') var_HOST = StringVar() var_HOST.set('127.0.0.1') var_PORT = StringVar() var_PORT.set('5000') # 图片 canvas = Canvas(root, height=650, width=600) image_file = PhotoImage(file='image/back.gif') canvas.create_image(0, 0, anchor='nw', image=image_file) canvas.pack(side='top') Label(root, text='HOST').place(x=50, y=50) Label(root, text='PORT').place(x=50, y=90) # 输入框 entry_HOST = Entry(root, textvariable=var_HOST) entry_HOST.place(x=160, y=50) entry_PORT = Entry(root, textvariable=var_PORT) entry_PORT.place(x=160, y=90) # 登录注册按钮 btn_login = Button(root, text='开始', command=lambda: Chess(root, entry_HOST.get(), entry_PORT.get()))# noqaE501 btn_login.place(x=170, y=130) root.mainloop()
def main(): #初始化pygame pygame.init() #初始化mixer pygame.mixer.init() #创建配置文件对象 gc = Game_Config() #设置屏幕大小和标题 pygame.display.set_caption(gc.gametitle) screen = pygame.display.set_mode(gc.backsize) #设置定时器,用于固定时间刷新屏幕,而不是一直不停的刷新,浪费CPU资源 FPS = 30 clock = pygame.time.Clock() #加载背景图片 background = pygame.image.load(gc.background_image).convert() #创建chess对象 chess = Chess(screen, gc) #主循环 while gc.running: #设置屏幕刷新频率 clock.tick(FPS) #检测事件 gf.check_event(gc, chess) #画出棋盘 #screen.blit(background,(0,0)) gf.draw_background(screen, background, gc) #添加棋子 chess.add_coin() #判断游戏是否结束 gf.game_is_over(gc, chess) #刷新屏幕 pygame.display.flip()
def PlayerVsPlayer(startState = None): chess = Chess() chess.print_board() #Allows play from a specific state if (startState != None): chess.input_state() chess.print_board() #Play Chess! while(True): move = input('Input move: ') move = chess.convert_move(move) game = chess.move(move) if (game == None print(print_move) chess.print_board() return(chess) elif (game == False): continue else: chess.print_board() return(chess) def main(): PlayerVsPlayer() main()
def main(): chess = Chess() root = tk.Tk() root.title("Chess") gui = GUI(root, chess) gui.pack() root.mainloop()
def button_actions(self): sender = self.sender() if sender.text() == "exit": self.close() elif sender.text() == "new game": self.scene.removeItem(self.game) del self.game self.game = Chess() self.scene.addItem(self.game)
def main(): game = Chess() player1 = Player(COLOR.white) player2 = Player(COLOR.black) game.add_player(player1) game.add_player(player2) game.start() test_check(game)
def on_mouse_press(self, x, y, button, modifiers): chess_temp = Chess( self.chess_type, caculate_index(x), caculate_index(y)) if not(is_chess_exists(chess_temp, self.chess_list)): self.chess_list.append(chess_temp) self.chess_img_list.append(chess_temp.img) self.board[chess_temp.x][chess_temp.y] = self.chess_type self.chess_type = switch_type(self.chess_type) a = is_victory(chess_temp.x, chess_temp.y, chess_temp.type, self.board)
def button_actions(self): sender = self.sender() if sender.text() == "Exit": self.socket.close() self.close() elif sender.text() == "New game": self.scene.removeItem(self.game) del self.game self.game = Chess(2) self.scene.addItem(self.game) elif sender.text() == "Connect": self.create_connection() elif sender.text() == "Resume": self.load_last_game() elif sender.text() == "Step resume": self.load_one_move()
def main(): game = Chess() player1 = Player(COLOR.white) player2 = Player(COLOR.black) game.add_player(player1) game.add_player(player2) game.start() test_pawn(game) test_rook(game) test_bishop(game) test_queen(game) test_king(game) test_knight(game) test_promoted_queen(game) test_players(player1, player2)
def __init__(self, size, sample_board): self.sample_board = sample_board pygame.init() self.Chess = Chess() self.screenX = size self.screenY = size flags = FULLSCREEN | DOUBLEBUF #flags = DOUBLEBUF self.screen = pygame.display.set_mode((size, size), flags) self.screen.set_alpha(None) self.piece_paths = self.get_piece_paths() self.piece_images = self.load_images() self.piece_being_held = None self.holding_piece = False pygame.display.set_caption('Chess') self.play_gui()
def run_game(): global flag #创建屏幕对象 pygame.init() qiset = Settings() screen = pygame.display.set_mode((qiset.screen_width, qiset.screen_height)) pygame.display.set_caption("五子棋") chess = Chess(screen) a = 0 #bg_color screen.fill(qiset.bg_color) #绘制棋盘 chess.chessboard(screen) #main() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == MOUSEBUTTONDOWN: pressed_array = pygame.mouse.get_pressed() for i in range(len(pressed_array)): if pressed_array[i]: if i == 0: #left button #chess.blitme(flag) a = chess.coordinate() if a: chess.save_chess() b = chess.win() if b == 1: print('白棋赢了') elif b == -1: print('黑棋赢了') elif i == 1: #mouse wheel pass elif i == 2: pass #right button #让最近绘制的屏幕可见 pygame.display.flip()
def main(): pos = Chess() layers=5 algorithm=Algorithm(pos,'black',layers) print_pos(pos) cnt1 = 0 delayTime = 25; while True: res = detect() move = str(res[0])+str(res[1]) print("move is") print(move) match=re.match('([a-h][1-8])'*2,move) if not match or (pos.format_move(move) not in pos.legal_moves()): print('Illegal Move') #move=input('Your move:') move = str(res[1])+str(res[0]) match=re.match('([a-h][1-8])'*2,move) if not match or (pos.format_move(move) not in pos.legal_moves()): continue #move=chb.determine_move() pos.move(move) print_pos(pos) opp_move=algorithm.best_move() newMove = str(opp_move[0])+str(ord('9')-ord(opp_move[1]))+str(opp_move[2])+ str(ord('9')-ord(opp_move[3])) print(newMove) start = opp_move[0:2] end = opp_move[2:] a = 63 - convertMove(newMove[0:2]) b = 63 - convertMove(newMove[2:]) if(pos.state.board[b//8][b%8]!='· '): ser.write((str(convertMove(newMove[0:2]))+","+str(convertMove(newMove[2:]))+"!").encode()) delayTime = 60 else: ser.write((str(convertMove(newMove[0:2]))+","+str(convertMove(newMove[2:]))+".").encode()) pos.move(opp_move) print_pos(pos) time.sleep(delayTime)
def run_game(): pygame.init() #初始化 st = Settings() screen = pygame.display.set_mode(st.setmode) #500*600的屏幕 pygame.display.set_caption('TicTacToe') #标题 image = pygame.image.load('materials/chessboard.bmp') #载入棋盘 chess = Chess() bigchess = BigChess() retract_button = Button(screen, (170, 50, 150, 40), text='Retract') #悔棋按钮 replay_button = Button(screen, (170, 110, 150, 40), text='Replay') #重玩按钮 windows = Windows(screen, 'Replay?', 'Yes', 'No', 150, 200) while True: screen.fill(st.bg_color) #背景色 screen.blit(image, st.top_left_corner) #在棋盘左上角位置绘制棋盘,注意跟棋盘的中心位置有关 f.check_keydown(chess, bigchess, windows, screen, st, retract_button, replay_button) #检测鼠标按动 retract_button.draw_button() #绘制悔棋按钮 replay_button.draw_button() #绘制重玩按钮 f.draw(chess, bigchess, screen, windows, st) #绘制棋子,框等 pygame.display.update() #更新屏幕
def main(): game = Chess() player1 = Player(COLOR.white) player2 = Player(COLOR.black) game.add_player(player1) game.add_player(player2) game.start() player1.game.turn = player1.color players = [player1, player2] turn = 0 while True: try: os.system('clear') player = players[turn] print(player.game) player.move(*input(f'{player.color.name} move: ').split()) turn = not turn except Exception as e: os.system('clear') print(f'{e.__class__.__name__}: {e}') input('Press return to continue...') continue
alfiere_1 = Bishop(input("metti posizione x: "), int(input("metti posizione y: "))) alfiere_1.possible_poss() print(alfiere_1.possible_poss()) # input_x = input("metti posizione x: ") # input_y = int(input("metti posizione y: ")) regina_1 = Queen('a', 3) regina_2 = Queen('h', 8) alfiere = Bishop('b', 3) #pedone = Pawn('g', 7) # questo è comodo. Può stampare a video perchè ha ereditato da ChessPiece __str__ #regina_1.pos_queen() c = Chess() c.set_piece(regina_1) c.set_piece(regina_2) c.set_piece(alfiere) print(c) #c.set_piece(pedone) # alfiere sparisce perchè pedone prende il suo posto. #print(c) #c.move_piece(regina_1, x_stat="r", y_stat=7) #print(c) # ricordati di fare gli unittest magari sulle classi... #devi implementare un metodo sulla scacchiera chiamato: #sposta_pezzo(...) #passando come parametri il pezzo che vuoi muovere e la nuova posizione.
n = 0 testing = False for arg in argv: if arg == "-test": testing = True else: try: n = int(arg) except ValueError: n = 0 while n < 4: try: n = int(input("Enter number of queens: ")) except ValueError: n = 0 chess = Chess(n) time = clock() chess.solve() time = int((clock() - time) * 1000) if testing: print( str(chess.steps()) + "\t" + str(chess.discards()) + "\t" + str(time)) else: print(chess) print("Solved in", chess.steps(), "steps. Time:", time, "ms.")
def __init__(self): self.chess = Chess() self.view = View()
def PlayerVsAI(startState, robot=False): chess = Chess() #Open Serial Port if (robot == True): port = open_port() while(True): player = input("Input Human Player's Color ('white' or 'black'): ") if (player == 'white'): computer = 'black' break elif (player == 'black'): computer = 'white' break else: print("Error incorrect color/n") print(); #Send player color information to Arduino when it is ready to recieve if (robot == True): ready = '' while(ready != 'R'): ready = arduino_ready(port) send_input(port, player) #Allows play from a specific state if (startState != None): chess.input_state() chess.print_board() #Max Recommended Difficulty: 5 layers. Averages around 15 seconds per move. layers = 5 algorithm = Algorithm(chess, computer, layers) #Play Chess! while(True): if (chess.state.turn == player): if (robot == True): serial_input = None move = recieve_input(port) move = chess.coordinate_to_notation(move) move = chess.convert_move(move) else: move = input('Input move: ') move = chess.convert_move(move) else: #Comments for move timing #start_time = time.time() move = algorithm.best_move() #end_time = time.time() #print("Move time: {}".format(end_time - start_time)) #If ChessBot is connected, send move via serial port if (robot == True): serial_input = chess.convert_serial_move(move) print_move = chess.convert_move(move) game = chess.move(move) if (robot == True and serial_input != None): send_input(port, serial_input) #Ensure game has not ended before if (game == None): print(print_move) chess.print_board() return(chess) elif (game == False): continue else: print(print_move) chess.print_board() return(chess)
import pygame as pg from chess import Chess pg.init() WIDTH, HEIGHT = 800, 800 DISPLAYWINDOW = pg.display.set_mode((WIDTH, HEIGHT)) ChessObj = Chess() def get_square_under_mouse(): mouse_pos = pg.mouse.get_pos() x, y = (pos // ChessObj.sizeOfSquare for pos in mouse_pos) return (x, y) def GameLoop(): sqSelected = () playerClicks = [] clock = pg.time.Clock() displayPossibleMove = [] while 1: ChessObj.Display(DISPLAYWINDOW) for event in pg.event.get(): if event.type == pg.QUIT: quit() if event.type == pg.MOUSEBUTTONDOWN: y, x = get_square_under_mouse()
def start_game(self): """Function containing main game loop""" # chess board offset self.board_offset_x = 0 self.board_offset_y = 50 self.board_dimensions = (self.board_offset_x, self.board_offset_y) # get location of chess board image board_src = os.path.join(self.resources, "board.png") # load the chess board image self.board_img = pygame.image.load(board_src).convert() # get the width of a chess board square square_length = self.board_img.get_rect().width // 8 # initialize list that stores all places to put chess pieces on the board self.board_locations = [] # calculate coordinates of the each square on the board for x in range(0, 8): self.board_locations.append([]) for y in range(0, 8): self.board_locations[x].append([self.board_offset_x+(x*square_length), self.board_offset_y+(y*square_length)]) # get location of image containing the chess pieces pieces_src = os.path.join(self.resources, "pieces.png") # create class object that handles the gameplay logic self.chess = Chess(self.screen, pieces_src, self.board_locations, square_length) # game loop while self.running: self.clock.tick(5) # poll events for event in pygame.event.get(): # get keys pressed key_pressed = pygame.key.get_pressed() # check if the game has been closed by the user if event.type == pygame.QUIT or key_pressed[K_ESCAPE]: # set flag to break out of the game loop self.running = False elif key_pressed[K_SPACE]: self.chess.reset() winner = self.chess.winner if self.menu_showed == False: self.menu() elif len(winner) > 0: self.declare_winner(winner) else: self.game() # for testing mechanics of the game #self.game() #self.declare_winner(winner) # update display pygame.display.flip() # update events pygame.event.pump() # call method to stop pygame pygame.quit()
def __init__(self): super(MainWindow, self).__init__() self.scene = QGraphicsScene(self) self.game = Chess(2) self.scene.addItem(self.game) self.scene.setSceneRect(0, 0, 360, 360) view = QGraphicsView(self.scene, self) layout = QGridLayout() self.info_window = QTextEdit() self.info_window.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.MinimumExpanding) self.info_window.setFocusPolicy(Qt.NoFocus) self.message_line = QLineEdit() self.message_line.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.MinimumExpanding) self.message_line.setFocusPolicy(Qt.StrongFocus) self.message_line.returnPressed.connect(self.send_msg) connect_button = QPushButton("Connect", self) connect_button.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.MinimumExpanding) connect_button.clicked.connect(self.button_actions) connect_button.setFocusPolicy(Qt.NoFocus) btn_new_game = QPushButton("New game", self) btn_new_game.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.MinimumExpanding) btn_new_game.clicked.connect(self.button_actions) btn_new_game.setFocusPolicy(Qt.NoFocus) btn_exit = QPushButton("Exit", self) btn_exit.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.MinimumExpanding) btn_exit.clicked.connect(self.button_actions) btn_exit.setFocusPolicy(Qt.NoFocus) btn_last_game = QPushButton("Resume", self) btn_last_game.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.MinimumExpanding) btn_last_game.clicked.connect(self.button_actions) btn_last_game.setFocusPolicy(Qt.NoFocus) btn_step_resume = QPushButton("Step resume", self) btn_step_resume.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.MinimumExpanding) btn_step_resume.clicked.connect(self.button_actions) btn_step_resume.setFocusPolicy(Qt.NoFocus) layout.addWidget(view, 0, 0, 8, 8) layout.addWidget(btn_new_game, 8, 0, 1, 8) layout.addWidget(btn_exit, 9, 0, 1, 8) layout.addWidget(connect_button, 10, 0, 1, 8) layout.addWidget(btn_last_game, 11, 0, 1, 8) layout.addWidget(btn_step_resume, 12, 0, 1, 8) layout.addWidget(self.info_window, 0, 9, 12, 4) layout.addWidget(self.message_line, 12, 9, 1, 4) self.setLayout(layout) self.setGeometry(1000, 300, 650, 560) self.setCacheMode(QGraphicsView.CacheBackground) self.setWindowTitle("Chess-server") self.socket = None self.th1 = None self.th2 = None self.resume_idx = 0 self.doc = minidom.Document() self.root = self.doc.createElement('game') self.doc.appendChild(self.root)
def main_menu(self): motd = "An unintuitive chess game by Darren Kearney." # Fancy ascii art title_art = """ 8\"\"\"\"8 8 8 \" eeeee eeeeeee eeeeeee eeeee eeeee eeeee 8 e eeeee eeee 8e 8 88 8 8 8 8 8 8 8 8 8 8 8 8 8e 8 8 8 8 88 8 8 8e 8 8 8e 8 8 8eee8 8e 8 8e 8 88 8e 8e 8 8eee 88 e 8 8 88 8 8 88 8 8 88 8 88 8 88 8 88 88 88 8 88 88eee8 8eee8 88 8 8 88 8 8 88 8 88 8 88ee8 88eee 88 88 8 88ee 8\"\"\"\"8 8 \" e e eeee eeeee eeeee 8e 8 8 8 8 \" 8 \" 88 8eee8 8eee 8eeee 8eeee 88 e 88 8 88 88 88 88eee8 88 8 88ee 8ee88 8ee88 """ title_string = self.colour_gradientify_title_text(title_art) print(u"\n{}\n".format(title_string)) print( "\n {}\n https://github.com/darrenkearney/command-line-chess\n" .format(motd)) self.available_options = [1, 2, 3, 4, 0] if self.is_game_running == False: self.available_options.remove(2) resume_msg = "(Not available)" items = [ 'Start a new game', '(Resume not available)', 'Load a saved game', 'Options' ] else: resume_msg = '' items = [ 'Start a new game', 'Resume current game', 'Load a saved game', 'Options' ] message_obj = { 'message': 'Start menu:', 'items': items, 'available_options': self.available_options } choice = self.multi_choice_input(message_obj) if choice == 1: # Initialize new game of chess self.chess = Chess() # Clean up menu options self.is_game_running = True self.available_options.append(2) # Run the game self.run_chess(self.chess) elif choice == 2: if self.is_game_running == False: print("Cannot resume - no current game.") self.get_view("MAIN_MENU") else: self.run_chess(self.chess) elif choice == 3: self.chess.do_command('load') self.run_chess(self.chess) elif choice == 4: self.get_view("SETTINGS") elif choice == 0: print("\n Thanks for playing. Bye! \n") exit()
from chess import Chess chess = Chess() while True: chess.status_manager()
def __init__(self): self.chess = Chess()