def run_game(): """运行游戏""" # 初始化游戏屏幕 pygame.init() # 创建时钟对象 (可以控制游戏循环频率) clock = pygame.time.Clock() # 配置实例化 ck_settings = Settings() screen = pygame.display.set_mode((ck_settings.width, ck_settings.height)) pygame.display.set_caption('五子棋游戏') # namedtuple创建类似于元组的数据类型,除了可以用索引访问,能够迭代,还能用属性名访问数据 position = namedtuple('Position', ['x', 'y']) # 创建实例 cb = Checkerboard(ck_settings, screen, position) # 实例化面板信息 infopanel = Infopanel(ck_settings, screen) while ck_settings.game_active: # 绘制棋盘 cb.draw_board() # 绘制面板信息 infopanel.draw_info(ck_settings.prompt_info) # 检查玩家事件并更新棋盘 gf.check_events(ck_settings, cb, position) # 让最近绘制的屏幕可见 pygame.display.flip() # 通过时钟对象指定循环频率 clock.tick(60) # 每秒循环60次
class Game(object): u""" Controlling class for a game of checkers """ def __init__(self, black_player, white_player): u""" Initialize a new game """ self.black_player = black_player self.white_player = white_player self.chb = Checkerboard() self.chb.setup_new_board() self.black_player.color = u'black' self.black_player.checkerboard = self.chb self.black_player.checkers = self.chb.black_checkers self.white_player.color = u'white' self.white_player.checkerboard = self.chb self.white_player.checkers = self.chb.white_checkers self.pos_counter = collections.Counter() def start_game(): u""" Begin play """ pass
def Gameover2(): game = Checkerboard() r1 = [0, 0, 0, 0, 0, 0, 0, 0] r2 = [0, 2, 0, 0, 0, 2, 0, 0] r3 = [0, 0, 1, 0, 1, 0, 0, 0] r4 = [0, 0, 0, -2, 0, 0, 0, 0] r5 = [0, 0, 2, 0, 1, 0, 0, 0] r6 = [0, 1, 0, 0, 0, 1, 0, 0] r7 = [0, 0, 0, 0, 0, 0, 0, 0] r8 = [0, 0, 0, 0, 0, 0, 0, 0] game.board = [r1, r2, r3, r4, r5, r6, r7, r8] game.turn = -1 Test2 = TwoPlayers() Test2.enterName("A","B") # The first player A (first one who enters the name) corresponds to chess piece labeled as 1, who wins this game. The second player B (second one who enters the name) corresponds to chess piece labeled as -1, who loses the game. Test2.gameProcess(game) # Should not do anything other then print out "The game is over. " because clearly the player B loses the game by not being able to move his chess piece for his turn. Test2.gameOver(game) # Should print out "A won the game!"
def Gameover1(): game = Checkerboard() r1 = [0, 0, 0, 0, 0, 0, 0, 0] r2 = [0, 0, 0, 0, 0, 0, 0, 0] r3 = [0, 0, 0, 0, 0, 0, 0, 0] r4 = [0, 0, 0, 0, 0, 0, 0, 0] r5 = [0, 0, 0, 0, 0, 0, 0, 0] r6 = [-1, 0, -1, 0, -1, 0, -1, 0] r7 = [0, -1, 0, -1, 0, -1, 0, -1] r8 = [-1, 0, -1, 0, -1, 0, -1, 0] game.board = [r1, r2, r3, r4, r5, r6, r7, r8] game.turn = 1 Test1 = TwoPlayers() Test1.enterName("A","B") # The first player A (first one who enters the name) corresponds to chess piece labeled as 1, who loses this game. The second player B (second one who enters the name) corresponds to chess piece labeled as -1, who wins the game. Test1.gameProcess(game) # Should not do anything other then print "The game is over. " because clearly the player A loses the game by losing all his chess pieces. Test1.gameOver(game) # Should print out "B won the game!"
def run_process(args, share_model, board_max, n_rows, rank): from checkerboard import Checkerboard, BoardRender board = Checkerboard(board_max, n_rows) board_render = BoardRender(board_max, render_off=True, inline_draw=True) board_render.clear() data_buffer = deque(maxlen=100000) Ts = [] Trewards = [] TQmax = [] for episode in range(1000): random.seed(time.time()) board.reset() board_render.clear() """ start a self-play game using a MCTS player, reuse the search tree store the self-play data: (state, mcts_probs, z) """ p1, p2 = board.players states, mcts_probs, current_players = [], [], [] for step in range(10000): if len(data_buffer) > 32: loss, entropy = agent.learn(data_buffer) # print('loss : ',loss,' entropy : ',entropy) move, move_probs = agent.get_action(board, temp=1.0, return_prob=1) # store the data states.append(board.current_state()) mcts_probs.append(move_probs) current_players.append(board.current_player) # perform a move board.step(move) board_render.draw(board.states) end, winner = board.game_end() if end: # winner from the perspective of the current player of each state winners_z = np.zeros(len(current_players)) if winner != -1: winners_z[np.array(current_players) == winner] = 1.0 winners_z[np.array(current_players) != winner] = -1.0 #reset MCTS root node agent.reset_player() if winner != -1: print("Game end. Winner is player:", winner) else: print("Game end. Tie") # return winner, zip(states, mcts_probs, winners_z) play_data = zip(states, mcts_probs, winners_z) ex_play_data = get_equi_data(play_data, board_max, board_max) data_buffer.extend(ex_play_data) break episode += 1
def __init__(self, black_player, white_player): u""" Initialize a new game """ self.black_player = black_player self.white_player = white_player self.chb = Checkerboard() self.chb.setup_new_board() self.black_player.color = u'black' self.black_player.checkerboard = self.chb self.black_player.checkers = self.chb.black_checkers self.white_player.color = u'white' self.white_player.checkerboard = self.chb self.white_player.checkers = self.chb.white_checkers self.pos_counter = collections.Counter()
def AIMultipleJumps(): game = Checkerboard() r1 = [0, 0, 1, 0, 0, 0, 0, 0] r2 = [0, 0, 0, -1, 0, 0, 0, 0] r3 = [0, 0, 0, 0, 0, 0, 0, 0] r4 = [0, 0, 0, 0, 0, -1, 0, 0] r5 = [0, 0, 0, 0, 0, 0, 0, 0] r6 = [0, 0, 0, 0, 0, 0, 0, 0] r7 = [0, 0, 0, 0, 0, 0, 0, 0] r8 = [0, 0, 0, 0, 0, 0, 0, 0] game.board = [r1, r2, r3, r4, r5, r6, r7, r8] game.turn = 1 Test4 = SinglePlayer() Test4.state = game Test4.turn = game.turn Test4.decisionMove() # AI should make the decision of double capturing as requierd by the rule of the game. print (Test4.state) # Print out the final result after AI's move, which should be only the chess piece 1 moving from (1,3) to (5,7).
def AIAvoidBeingCaptured(): game = Checkerboard() r1 = [0, 0, 0, 0, 0, 0, 0, 0] r2 = [0, 0, -1, 0, 0, 0, 0, 0] r3 = [1, 0, 0, 0, 0, 0, 0, 0] r4 = [0, 1, 0, 0, 0, 0, 0, 0] r5 = [0, 0, -1, 0, 0, 0, 0, 0] r6 = [0, 0, 0, 0, 0, 0, 0, 0] r7 = [0, 0, 0, 0, 0, 0, 0, 0] r8 = [0, 0, 0, 0, 0, 0, 0, 0] game.board = [r1, r2, r3, r4, r5, r6, r7, r8] game.turn = -1 Test5 = SinglePlayer() Test5.state = game Test5.turn = game.turn print (game) Test5.decisionMove() # AI should make the decision of always moving the -1 chess piece at (5,3) to (4,4) because it is in danger of being captured. print (Test5.state) # Print out the final result.
def MultipleJumps(): game = Checkerboard() r1 = [0, 0, 1, 0, 0, 0, 0, 0] r2 = [0, 0, 0, -1, 0, 0, 0, 0] r3 = [0, 0, 0, 0, 0, 0, 0, 0] r4 = [0, 0, 0, 0, 0, -1, 0, 0] r5 = [0, 0, 0, 0, 0, 0, 0, 0] r6 = [0, 0, 0, 0, 0, 0, 0, 0] r7 = [0, 0, 0, 0, 0, 0, 0, 0] r8 = [0, 0, 0, 0, 0, 0, 0, 0] game.board = [r1, r2, r3, r4, r5, r6, r7, r8] game.turn = 1 Test3 = TwoPlayers() Test3.enterName("A","B") print (game) Test3.gameProcess(game) # Should have an interactive process asking A to "choose the piece to move" and "where to move the piece to", and a multiple captures/multiple jumps process is required if the player choose the do the first capture. # This test of multiple jumps/captures is shown by the log file of the game too. Test3.gameOver(game) # SHould print "A won the game! " after the interactive process.
def AIHaveToMoveRealSituation(): game = Checkerboard() r1=[0, 0, 0, 0, 0, 0, 0, 0] r2=[1, 0, 1, 0, 1, 0, 1, 0] r3=[0, 1, 0, 1, 0, 1, 0, 1] r4=[1, 0, -1, 0, 0, 0, 1, 0] r5=[0, -1, 0, -1, 0, -1, 0, 1] r6=[0, 0, -1, 0, -1, 0, -1, 0] r7=[0, -1, 0, -1, 0, -1, 0, 0] r8=[0, 0, 0, 0, -1, 0, 0, 0] game.board = [r1, r2, r3, r4, r5, r6, r7, r8] game.turn = 1 Test6 = SinglePlayer() Test6.state = game Test6.turn = game.turn print (Test6.state) print ("This is the AI's move: ") print ("\n") Test6.decisionMove() # The AI only have to choices here -- to either move the chess piece at (3,4) or the one at (3,6) to the position (4,5). This is not a safe move, but AI does not have choice so has to do it. print (Test6.state) # Print out the final result.
def run_process(args, share_model, board_max, n_rows, rank): from checkerboard import Checkerboard, BoardRender board = Checkerboard(board_max, n_rows) board_render = BoardRender(board_max, render_off=False, inline_draw=True) board_render.clear() board_render.draw(board.states) for episode in range(1): random.seed(time.time()) board.reset() board_render.clear() """ start a self-play game using a MCTS player, reuse the search tree store the self-play data: (state, mcts_probs, z) """ p1, p2 = board.players player = input('select player 1: balck , 2 : white') if player == '1': play_step = 0 else: play_step = 1 for step in range(10000): if step % 2 == play_step: ss = input('input x,y:') pos = ss.split(',') if pos == 'q': return move = int(pos[0]) + int(pos[1]) * board_max print('movd ', move) else: move, move_probs = agent.get_action(board, temp=1.0, return_prob=1) board.step(move) board_render.draw(board.states) end, winner = board.game_end() if end: # winner from the perspective of the current player of each state agent.reset_player() if winner != -1: print("Game end. Winner is player:", winner) else: print("Game end. Tie") # return winner, zip(states, mcts_probs, winners_z) break episode += 1
def human_process(args, share_model, rank, self_play, shared_lr_mul, shared_g_cnt, shared_q, lock): print('human play') self_play = False board_max = args.board_max from agent import Agent_MCTS agent = Agent_MCTS(args, 5, 800, self_play, shared_lr_mul, shared_g_cnt) with lock: agent.model_update(share_model) from checkerboard import Checkerboard, BoardRender board = Checkerboard(board_max, args.n_rows) board_render = BoardRender(board_max, render_off=False, inline_draw=True) board.reset() board_render.clear() board_render.draw(board.states) p1, p2 = board.players player = input('select player 1: balck , 2 : white') if player == '1': play_step = 1 else: play_step = 0 for step in range(10000): if step // 2 % 2 == play_step: ss = input('input x,y:') pos = ss.split(',') if pos == 'q': return move = int(pos[0]) + int(pos[1]) * board_max print('movd ', move) else: move, move_probs = agent.get_action(board) board.step(move) board_render.draw(board.states) end, winner = board.game_end() if end: # winner from the perspective of the current player of each state agent.reset_player() if winner != -1: print("Game end. Winner is player:", winner) else: print("Game end. Tie") # return winner, zip(states, mcts_probs, winners_z) return
def act_process(args, share_model, rank, self_play, shared_lr_mul, shared_g_cnt, shared_q, lock): print(rank) board_max = args.board_max from agent import Agent_MCTS agent = Agent_MCTS(args, 5, 100, self_play, shared_lr_mul, shared_g_cnt) from checkerboard import Checkerboard, BoardRender board = Checkerboard(board_max, args.n_rows) board_render = BoardRender(board_max, render_off=True, inline_draw=False) board_render.clear() Ts = [] Tloss = [] Tentropy = [] try: for episode in range(10000): start_time = time.time() with lock: agent.model_update(share_model) random.seed(time.time()) board.reset() board_render.clear() board_render.draw(board.states) """ start a self-play game using a MCTS player, reuse the search tree store the self-play data: (state, mcts_probs, z) """ p1, p2 = board.players states, mcts_probs, current_players = [], [], [] # list_loss = [] # list_entropy = [] for step in range(10000): move, move_probs = agent.get_action(board, temp=1.0) # store the data states.append(board.current_state()) mcts_probs.append(move_probs) current_players.append(board.current_player) # perform a move board.step(move) board_render.draw(board.states) end, winner = board.game_end() if end: # time.sleep(1) # winner from the perspective of the current player of each state winners_z = np.zeros(len(current_players)) if winner != -1: winners_z[np.array(current_players) == winner] = 1.0 winners_z[np.array(current_players) != winner] = -1.0 #reset MCTS root node agent.reset_player() if winner != -1: print(rank, "Game end. Winner is player:", winner, 'total_step :', step, 'time:', time.time() - start_time) else: print(rank, "Game end. Tie", 'total_step :', step, 'time:', time.time() - start_time) # return winner, zip(states, mcts_probs, winners_z) play_data = zip(states, mcts_probs, winners_z) ex_play_data = get_equi_data(play_data, board_max, board_max) shared_q.put(ex_play_data) break # # plot_data # if len(data_buffer) > args.batch_size and len(list_loss)!=0: # # Ts.append(episode) # Tloss.append(list_loss) # Tentropy.append(list_entropy) # _plot_line(Ts, Tloss, 'loss', path='./') # _plot_line(Ts, Tentropy, 'entropy', path='./') episode += 1 except: print(rank, 'except end')
def main(): pygame.init() screen = pygame.display.set_mode((screen_width, screen_height)) pygame.display.set_caption('Gomoku') # Font and font size font1 = pygame.font.SysFont('Arial', 35) font2 = pygame.font.SysFont('Arial', 65) fwidth, fheight = font2.size('Player Wins') # Draw the board and initiate the game checkerboard = Checkerboard(num_points) cur_runner = Black_Piece winner = None computer = AI(num_points, White_Piece) # Counting progress on who is winning black_win_count = 0 white_win_count = 0 # If the game is not over, then the following iteration goes while True: for event in pygame.event.get(): if event.type == QUIT: sys.exit() elif event.type == KEYDOWN: if event.key == K_RETURN: if winner is not None: winner = None cur_runner = Black_Piece checkerboard = Checkerboard(num_points) computer = AI(num_points, White_Piece) elif event.type == MOUSEBUTTONDOWN: if winner is None: pressed_array = pygame.mouse.get_pressed() if pressed_array[0]: mouse_pos = pygame.mouse.get_pos() click_point = _get_clickpoint(mouse_pos) if click_point is not None: if checkerboard.can_drop(click_point): winner = checkerboard.drop( cur_runner, click_point) if winner is None: cur_runner = _get_next(cur_runner) computer.get_opponent_drop(click_point) AI_point = computer.AI_drop() winner = checkerboard.drop( cur_runner, AI_point) if winner is not None: white_win_count += 1 cur_runner = _get_next(cur_runner) else: black_win_count += 1 else: print('Out of Bound') # Draw the grid _draw_board(screen) # Draw the existing pieces on the grid for i, row in enumerate(checkerboard.checkerboard): for j, cell in enumerate(row): if cell == Black_Piece.Value: _draw_piece(screen, Point(j, i), Black_Piece.Color) elif cell == White_Piece.Value: _draw_piece(screen, Point(j, i), White_Piece.Color) _draw_left_info(screen, font1, cur_runner, black_win_count, white_win_count) # If a winner appears, then print the following txt. if winner: print_msg(screen, font2, (screen_width - fwidth) // 2, (screen_height - fheight) // 2, winner.Name + ' Wins', Red_Color) pygame.display.flip()
def run_process(args, share_model, board_max, rank): from checkerboard import Checkerboard env = Checkerboard(board_max, args.render) from agent import Agent_rainbow B_Agent = Agent_rainbow(args) W_Agent = Agent_rainbow(args) B_Agent.main_dqn = B_share_model W_Agent.main_dqn = W_share_model B_Agent.optimizer = optim.Adam(B_share_model.parameters(), lr=args.lr, eps=args.adam_eps) W_Agent.optimizer = optim.Adam(W_share_model.parameters(), lr=args.lr, eps=args.adam_eps) # from memory import PER_Memory # memory = PER_Memory(args) data_buffer = deque(maxlen=args.memory_capacity) """ main loop """ global_count = 0 episode = 0 W_Agent.target_dqn_update() B_Agent.target_dqn_update() W_Agent.train() B_Agent.train() Ts = [] Trewards = [] TQmax = [] while episode < args.max_episode_length: random.seed(time.time()) T = 0 turn = 0 max_action_value = -999999999999999 state = env.reset() evaluation = False total_reward = 0 if episode % args.evaluation_interval == 0: evaluation = True # args.epsilon -= 0.8/args.max_episode_length while T < args.max_step: action_value = -999999999999999 if T % 2 == 0: Agent_ptr = B_Agent turn = env.black else: Agent_ptr = W_Agent turn = env.white if not evaluation and (random.random() <= args.epsilon or global_count < args.learn_start): action = env.get_random_xy_flat() else: action, action_value = Agent_ptr.get_action(state) max_action_value = max(max_action_value, action_value) next_state, reward, done, _ = env.step_flat(action, turn) total_reward += reward memory.push(td_error, [state, action, reward, next_state, done]) state = next_state # replay_interval, target_update_interval only used odd number if not evaluation and global_count % args.replay_interval == 0 and global_count > args.learn_start: Agent_ptr.learn(memory) Agent_ptr.reset_noise() if not evaluation and global_count % args.target_update_interval == 0: Agent_ptr.target_dqn_update() T += 1 global_count += 1 if done: B_Agent.reset_noise() W_Agent.reset_noise() if args.render: env.render() break if evaluation: print('episode : ', episode, ' step : ', T, ' max_action ', max_action_value, 'total_reward : ', total_reward) Ts.append(episode) Trewards.append([total_reward]) TQmax.append([max_action_value]) _plot_line(Ts, Trewards, 'rewards_' + args.name + '_' + str(rank), path='results') _plot_line(Ts, TQmax, 'Q_' + args.name + '_' + str(rank), path='results') if episode % args.save_interval == 0: print('save') B_Agent.save('B' + args.name) W_Agent.save('W' + args.name) episode += 1
def main(): pygame.init() screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption('五子棋') font1 = pygame.font.SysFont('SimHei', 36) font2 = pygame.font.SysFont('SimHei', 72) fwidth, fheight = font2.size('黑方获胜') checkerboard = Checkerboard(Line_Points) cur_runner = BLACK_CHESSMAN winner = None while True: for event in pygame.event.get(): if event.type == QUIT: sys.exit() elif event.type == KEYDOWN: if event.key == K_RETURN: if winner is not None: winner = None cur_runner = BLACK_CHESSMAN checkerboard = Checkerboard(Line_Points) elif event.type == MOUSEBUTTONDOWN: if winner is None: pressed_array = pygame.mouse.get_pressed() if pressed_array[0]: mouse_pos = pygame.mouse.get_pos() click_point = _get_clickpoint(mouse_pos) if click_point is not None: if checkerboard.can_drop(click_point): winner = checkerboard.drop( cur_runner, click_point) if cur_runner == BLACK_CHESSMAN: cur_runner = WHITE_CHESSMAN else: cur_runner = BLACK_CHESSMAN else: print('超出棋盘区域') # 画棋盘 _draw_checkerboard(screen) # 画棋盘上已有的棋子 for i, row in enumerate(checkerboard.checkerboard): for j, cell in enumerate(row): if cell == BLACK_CHESSMAN.Value: _draw_chessman(screen, Point(j, i), BLACK_CHESSMAN.Color) elif cell == WHITE_CHESSMAN.Value: _draw_chessman(screen, Point(j, i), WHITE_CHESSMAN.Color) _draw_chessman_pos(screen, (SCREEN_HEIGHT + Stone_Radius2, Start_X + 20), BLACK_STONE_COLOR) _draw_chessman_pos( screen, (SCREEN_HEIGHT + Stone_Radius2, Start_X + 20 + Stone_Radius2 * 3), WHITE_STONE_COLOR) if winner: print_text(screen, font2, (SCREEN_WIDTH - fwidth) // 2, (SCREEN_HEIGHT - fheight) // 2, winner.Name + '获胜', RED_COLOR) if cur_runner == BLACK_CHESSMAN: print_text(screen, font1, RIGHT_INFO_POS_X, Start_X, '获胜' if winner else '落子中', BLUE_COLOR) else: print_text(screen, font1, RIGHT_INFO_POS_X, Start_X + Stone_Radius2 * 3, '获胜' if winner else '落子中', BLUE_COLOR) pygame.display.flip()
# Copyright (C) 2019 Davide De Tommaso # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <https://www.gnu.org/licenses/> from checkerboard import Checkerboard # Default checkerboard: 6x8 inner corners, 7 row x 9 columns Checkerboard().run() # Custom checkerboard: 2x2 inner corners, 3 row x 3 columns #Checkerboard(row_corners=2, col_corners=2).run() # Custom checkerboard: 9x13 inner corners, 10 row x 14 columns, bg_color=red, # and it displays on the screen with id=1 in a multiple screen configuration #Checkerboard(row_corners=9, col_corners=13, padding_min=50, screen_id=1, bg_color=(255, 0, 0)).run()
def main(): pygame.init() screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption('五子棋') font1 = pygame.font.SysFont('SimHei', 32) font2 = pygame.font.SysFont('SimHei', 72) fwidth, fheight = font2.size('黑方获胜') checkerboard = Checkerboard(Line_Points) cur_runner = BLACK_CHESSMAN winner = None computer = AI(Line_Points, WHITE_CHESSMAN) black_win_count = 0 white_win_count = 0 while True: for event in pygame.event.get(): if event.type == QUIT: sys.exit() elif event.type == KEYDOWN: if event.key == K_RETURN: if winner is not None: winner = None cur_runner = BLACK_CHESSMAN checkerboard = Checkerboard(Line_Points) computer = AI(Line_Points, WHITE_CHESSMAN) elif event.type == MOUSEBUTTONDOWN: if winner is None: pressed_array = pygame.mouse.get_pressed() if pressed_array[0]: mouse_pos = pygame.mouse.get_pos() click_point = _get_clickpoint(mouse_pos) if click_point is not None: if checkerboard.can_drop(click_point): winner = checkerboard.drop(cur_runner, click_point) if winner is None: cur_runner = _get_next(cur_runner) computer.get_opponent_drop(click_point) AI_point = computer.AI_drop() winner = checkerboard.drop(cur_runner, AI_point) if winner is not None: white_win_count += 1 cur_runner = _get_next(cur_runner) else: black_win_count += 1 else: print('超出棋盘区域') # 画棋盘 _draw_checkerboard(screen) # 画棋盘上已有的棋子 for i, row in enumerate(checkerboard.checkerboard): for j, cell in enumerate(row): if cell == BLACK_CHESSMAN.Value: _draw_chessman(screen, Point(j, i), BLACK_CHESSMAN.Color) elif cell == WHITE_CHESSMAN.Value: _draw_chessman(screen, Point(j, i), WHITE_CHESSMAN.Color) _draw_left_info(screen, font1, cur_runner, black_win_count, white_win_count) if winner: print_text(screen, font2, (SCREEN_WIDTH - fwidth)//2, (SCREEN_HEIGHT - fheight)//2, winner.Name + '获胜', RED_COLOR) pygame.display.flip()
from ant import Ant from game import Game from window import Window from checkerboard import Checkerboard window = Window("Langton Ant") width = 150 height = 150 checkerboard = Checkerboard(window, window.width, window.height, 'white') checkerboard.create_board(width, height) ant = Ant(width / 2, height / 2, 'black') game = Game(ant, checkerboard) for i in range(0, 12000): game.run() window.update() window.display()
from checkerboard import Checkerboard from twoPlayers import TwoPlayers from singlePlayer import SinglePlayer next="1" # Main file for running the checker game -- everything gets "assembled" as a whole here: while next == "1": game = Checkerboard() mode = input("Welcome to checkers. Please input A for two players mode and B for single player mode: ") if mode == "A": twoPlayersGame = TwoPlayers() Name1 = input("Enter the name for the player who will go first: ") Name2 = input("Enter the name for the player who will go second: ") twoPlayersGame.enterName(Name1, Name2) twoPlayersGame.gameStart(game) twoPlayersGame.gameProcess(game) twoPlayersGame.gameOver(game) next = input("Type 0 to exist the game; type any other key to continue: ") if next == "0": break else: next="1" continue # continue the while loop and restart the game. elif mode == "B": AI = SinglePlayer() Player = TwoPlayers() player = raw_input("Enter your name: ") turn = raw_input("Do you want to go first (using chess piece '1') or second (using chess piece '-1')? ") while turn!="first" and turn!="second": print ("Invalid input. Please enter first or second.") turn = raw_input("Do you want to go first or second? ")
def main(): pygame.init() screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption('Gobang') font1 = pygame.font.SysFont('SimHei', 36) font2 = pygame.font.SysFont('SimHei', 72) fwidth, fheight = font2.size('Black Win') checkerboard = Checkerboard(Line_Points) # 白棋先走 cur_runner = WHITE_CHESSMAN winner = None while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() elif event.type == KEYDOWN: # 回车键重新开始 if event.key == K_RETURN: winner = None cur_runner = WHITE_CHESSMAN checkerboard = Checkerboard(Line_Points) elif event.type == MOUSEBUTTONDOWN: if winner is None: # pressed_array获得一个三元组(1, 0, 0)记录按下的是左键 pressed_array = pygame.mouse.get_pressed() # print(pressed_array, "pressed_array") if pressed_array[0]: # mouse_pos表示鼠标按下时相对于窗口的位置 mouse_pos = pygame.mouse.get_pos() # print(mouse_pos, "mouse_pos") # click_point表示鼠标按下时相对棋盘的落子位置(已经转化为具体坐标位置) click_point = _get_clickpoint(mouse_pos) # print(click_point, "click_point") if click_point is not None: if checkerboard.can_drop(click_point): winner = checkerboard.drop( cur_runner, click_point) if winner == None: if cur_runner == BLACK_CHESSMAN: cur_runner = WHITE_CHESSMAN else: cur_runner = BLACK_CHESSMAN # else: # print('超出棋盘区域') # 画棋盘 _draw_checkerboard(screen) # 画棋盘上已有的棋子 for i, row in enumerate(checkerboard.checkerboard): for j, cell in enumerate(row): if cell == BLACK_CHESSMAN.Value: _draw_chessman(screen, Point(j, i), BLACK_CHESSMAN.Color) elif cell == WHITE_CHESSMAN.Value: _draw_chessman(screen, Point(j, i), WHITE_CHESSMAN.Color) # 画状态栏棋子 _draw_chessman_pos(screen, (SCREEN_HEIGHT + Stone_Radius2, Start_X + 20), BLACK_STONE_COLOR) _draw_chessman_pos( screen, (SCREEN_HEIGHT + Stone_Radius2, Start_X + 20 + Stone_Radius2 * 3), WHITE_STONE_COLOR) if winner: print_text(screen, font2, (SCREEN_WIDTH - fwidth) // 2, (SCREEN_HEIGHT - fheight) // 2, winner.Name + 'Win', RED_COLOR) if cur_runner == BLACK_CHESSMAN: print_text(screen, font1, RIGHT_INFO_POS_X, Start_X, 'Win' if winner else 'ing...', BLUE_COLOR) else: print_text(screen, font1, RIGHT_INFO_POS_X, Start_X + Stone_Radius2 * 3, 'Win' if winner else 'ing...', BLUE_COLOR) pygame.display.flip()