def run(rows, columns, depth, weights): def update_board_with_matches(board, matches): for piece, clusters in matches: for r, c in clusters: board.update(r, c, type(piece)) b = Board.create_randomized_board(5, 6) # b = Board([Fire, Wood, Water, Dark, Light, Light, # Water, Fire, Water, Light, Heart, Light, # Fire, Water, Dark, Heart, Heart, Wood, # Light, Water, Light, Fire, Wood, Wood, # Dark, Heart, Dark, Light, Heart, Light], 5, 6) m = Board.create_empty_board(rows, columns) update_board_with_matches(m, b.get_matches()) h = GreedyDfs(weights) if False else PrunedBfs(weights) h.diagonals = True start = time.time() moves = h.solve(b, depth) performance = time.time() - start print('---------------------------------------------') print(b) print(m) print('run time : ' + str(performance)) print('best move score : ' + str(moves[0])) print('start : ' + str(moves[1][0])) print('moves : ' + str(moves[1][1:])) print(moves[2]) m = Board.create_empty_board(rows, columns) update_board_with_matches(m, moves[2].get_matches()) print(m)
def test_start_fen_black(self): board = Board() board.parse_fen(START_FEN) board.side = BLACK moves = board.moveGenerator.generate_all_moves() self.assertEqual(len(moves), 20)
class TestBoard: def setup_method(self, method): self.b = Board() self.valid_pos = {'row': 0, 'col': 1} self.invalid_pos = {'row': 0, 'col': -5} self.color = 'red' def test_default_board_size(self): assert len(self.b.grid) == 3 def test_board_is_seeded_with__none(self): flat_grid = self.b.flattened_grid() assert all(val is None for val in flat_grid) def test_board_set_with_invalid_pos(self): with pytest.raises(InvalidMoveError) as excinfo: self.b.set(self.invalid_pos, self.color) assert 'position is off the board' in str(excinfo.value) def test_board_set_valid(self): self.b.set(self.valid_pos, self.color) assert isinstance(self.b.get(self.valid_pos), Piece) def test_board_set_invalid(self): self.b.set(self.valid_pos, self.color) with pytest.raises(InvalidMoveError) as excinfo: self.b.set(self.valid_pos, self.color) assert 'Space allready occupied' in str(excinfo.value)
def main(): pygame.display.init() pygame.display.set_caption(TITLE) scrSize = (WIDTH + 1, HEIGHT + 1) if DRAW_GRID else (WIDTH, HEIGHT) screen = pygame.display.set_mode(scrSize) board = Board(screen, (WIDTH, HEIGHT), PIXEL_NUM, draw_grid=DRAW_GRID, map=MAP, animations=ANIMATIONS) # board = Board_cy(screen, (WIDTH, HEIGHT), PIXEL_NUM, # draw_grid=DRAW_GRID, map=MAP, animations=ANIMATIONS) isAlgorithmStarted = False while True: if (rv := runTime(board, isAlgorithmStarted)): if rv == 2: if not board.startAlgorithm(lambda: runTime(board, True)): break else: break
def search(self, n=10, retries=20): """ Attempts to find the optimal solution to the n-Queens problem using local search where the maximum number of retries is given. Each retry has a maximum of 'n' search steps. :param n: The maximum number of search steps for each retry. :param retries: The number of retries. :return: The optimum found by the local search algorithm. """ for retry in range(retries): curr_optimum = Board(self.size) for step in range(n): x = self.search_step(curr_optimum) if x is None: break curr_optimum = x if curr_optimum.cost() < self.optimal_cost: self.optimum = curr_optimum self.optimal_cost = curr_optimum.cost() if self.optimal_cost == 0: return self.optimum return self.optimum
def minimax(self, board, depth, alpha, beta, maximising_Player): """Method to perform alpha beta pruning""" valid_location = Board.valid_locations(board) is_terminal = Board.terminal_node(board) if depth == 0 or is_terminal: if is_terminal: if Board.so_won(board, self.no): return None, 100000 # always two values since I need space to save the column elif Board.so_won(board, 3 - self.no): return None, -100000 else: return None, 0 else: return None, self.value_function(board, self.no) if maximising_Player: score = -math.inf column = random.choice(valid_location) for selected_col in valid_location: row = Board.where_it_lands(board, selected_col) board_copy = board.copy() Board.play(board_copy, row, selected_col, self.no) new_score = self.minimax(board_copy, depth - 1, alpha, beta, False)[1] if new_score > score: score = new_score column = selected_col alpha = max(alpha, score) if alpha >= beta: break return column, score else: score = math.inf column = random.choice(valid_location) for selected_col in valid_location: row = Board.where_it_lands(board, selected_col) board_copy = board.copy() Board.play(board_copy, row, selected_col, 3 - self.no) new_score = self.minimax(board_copy, depth - 1, alpha, beta, True)[1] if new_score < score: score = new_score column = selected_col beta = min(beta, score) if alpha >= beta: break return column, score
def test_complex_fen_white_2(self): board = Board() complex_fen = "R6R/3Q4/1Q4Q1/4Q3/2Q4Q/Q4Q2/pp1Q4/kBNN1KB1 w -- 0 1" board.parse_fen(complex_fen) moves = board.moveGenerator.generate_all_moves() self.assertEqual(len(moves), 218)
def test_complex_fen_black(self): board = Board() complex_fen = "r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R b KQkq - 0 1" board.parse_fen(complex_fen) moves = board.moveGenerator.generate_all_moves() self.assertEqual(len(moves), 43)
def __init__(self, screen_width, screen_height): self.canvas = pygame.display.set_mode((screen_width, screen_height)) self.screen_width = screen_width self.screen_height = screen_height self.clock = pygame.time.Clock() self.helpers = Helpers() # class defines helper functions # indicates if board should be drawn in reverse i.e. black is on the bottom of the screen self.revesed_board = False self.square_loc = self.helpers.compute_square_locations( self.revesed_board) # --- Board related vars self.board = Board() self.board.parse_fen( START_FEN) # mate in two '3k4/8/8/3K4/8/8/1Q6/8 w --' self.move_history = [] # --- Engine process self.stub = None self.engine_info = None self.movetime = '1500' # default engine move time in ms # -- self.highlighted_moves = [] self.promotion_moves = [] # after promotion moves are drawn, this stores info about where each promotion move is drawn on the board self.promotion_choices = {} self.clicked_square_idx = None # --- Images # -- Squares dark_square = pygame.image.load( 'assets/square brown dark_png_128px.png') light_square = pygame.image.load( 'assets/square brown light_png_128px.png') black_square = pygame.image.load( 'assets/square gray dark _png_128px.png') highlight_check_square = pygame.image.load('assets/highlighted_1.png') highlight_square = pygame.image.load('assets/highlighted_2.png') highlight_move_square = pygame.image.load('assets/highlighted_3.png') self.dark_square = pygame.transform.scale(dark_square, (SQUARE_SIZE, SQUARE_SIZE)) self.light_square = pygame.transform.scale(light_square, (SQUARE_SIZE, SQUARE_SIZE)) self.black_square = pygame.transform.scale(black_square, (SQUARE_SIZE, SQUARE_SIZE)) self.highlight_check_square = highlight_check_square self.highlight_square = highlight_square self.highlight_move_square = highlight_move_square self.piece_images = self.helpers.load_assets() self.user_side = WHITE self.user_name = 'Player1' self.fen = '' self.last_move = '' self.in_check_sq = None self.engine_triggered = False
def test_large_board(self): player = Board(10, 10) cpu = Board(10, 10) self.assertIsInstance(player, Board) self.assertIsInstance(cpu, Board) self.assertEqual( player.render(), " 1 2 3 4 5 6 7 8 9 10 \nA . . . . . . . . . . \nB . . . . . . . . . . \nC . . . . . . . . . . \nD . . . . . . . . . . \nE . . . . . . . . . . \nF . . . . . . . . . . \nG . . . . . . . . . . \nH . . . . . . . . . . \nI . . . . . . . . . . \nJ . . . . . . . . . . " )
def __init__(self): pyxel.init(SCREEN_WIDTH, SCREEN_HEIGHT, caption="Pyxel Othello") pyxel.mouse(True) self.board = Board() self.current = 'black' self.black_player = RandomPlayer(pyxel, self.board, 'black') self.white_player = RandomPlayer(pyxel, self.board, 'white') self.winner = None self.previous_frame_count = 0 pyxel.run(self.update, self.draw)
def play_game(players, board): should_print = __name__ == '__main__' # prevent printing when running reports if should_print: print(board) print("============\n") turn = 0 while not Board.so_won(board, players[turn ^ 1].no) and len( Board.valid_locations(board)) > 0: if should_print: print("{}:".format(players[turn].name)) selected_col = players[turn].selector(board, -math.inf, math.inf, True) if Board.legal_check(board, selected_col): row = Board.where_it_lands(board, selected_col) Board.play(board, row, selected_col, players[turn].no) if should_print: Board.print_right_way(board) print("============\n") turn ^= 1 if Board.so_won(board, players[turn ^ 1].no): print("VICTORY FOR " + players[turn ^ 1].name) return players[turn ^ 1].name else: print("DRAW") return 'DRAW'
def __init__(self, pnames): """ :param pnames: An Array. Name of the players as Strings """ self.board = Board() self.players = tuple([Player(pn, self.board, self) for pn in pnames]) self.plookup = {p.getId(): p for p in self.players} self.lastRoll = None self.p = None self.getFirstPlayer() self.state = 0
def test_placing_ship(self): board = Board(4, 4) cruiser = Ship("Cruiser", 3) submarine = Ship("Submarine", 2) board.place(cruiser, ["A1", "A2", "A3"]) self.assertEqual(board.cells["A1"].ship, cruiser) self.assertEqual(board.cells["A2"].ship, cruiser) self.assertEqual(board.cells["A3"].ship, cruiser) self.assertTrue(board.cells["A1"].ship == board.cells["A3"].ship) # Test for overlap self.assertFalse(board.isValidPlacement(submarine, ["A1", "B1"]))
def reset_board(self): self.board = Board() self.board.parse_fen(START_FEN) self.move_history = [] self.movetime = '1500' self.reset_highlighted_moves() self.user_side = WHITE self.fen = '' self.last_move = '' self.in_check_sq = None self.engine_triggered = False
class TestMod(Mod): full_name = 'Bombastik Bomberman' quit = False def __init__(self): super(TestMod, self).__init__() self.add_bomb = False self.board = Board(self.config['board']['size']) x, y = self.board.get_size() for i in range(x): for j in range(y): Grid(i,j,self.board) self.pointer = Pointer(1,1,self.board) print "Press escape to quit" print "Use arrow keys to move" print "Enter to add a bomb" print "1 to add 100 bombs" print "r to remove all bombs" def handle_input(self, input): for key in input.get('keydown',[]): if key == 'escape': self.quit = True if key == 'return': self.add_bomb = True if key == 'up': self.pointer.y -= 1 if key == 'down': self.pointer.y += 1 if key == 'left': self.pointer.x -=1 if key == 'right': self.pointer.x += 1 if key == 'r': for tile in self.board.get_tiles_of_type(Bomb): tile.remove_from_board() print "Removing bombs" if key == '1': for i in range(99): Bomb(random.randint(0,self.board.width-1),random.randint(0,self.board.height-1), self.board) print "Adding 100 bombs" def update(self): if self.add_bomb: Bomb(self.pointer.x, self.pointer.y, self.board) self.add_bomb = False return self.quit
def expansion(self, child): """Second step of MCTS: Expand tree from the selected node if possible""" temp_board = self.board.copy() Board.play(temp_board, child[0], child[1], self.no) if Board.terminal_node(temp_board): self.N += 1 if Board.so_won(self.board, self.no): # MCTS won self.values[child[0]][child[1]] = (self.values[child[0]][child[1]] * (self.N - 1) + 1) / self.N return 1 elif Board.so_won(self.board, 3 - self.no): # Opponent won self.values[child[0]][child[1]] = (self.values[child[0]][child[1]] * (self.N - 1)) / self.N else: # Draw self.values[child[0]][child[1]] = (self.values[child[0]][child[1]] * (self.N - 1) + 0.5) / self.N else: self.simulation(child)
def action(board): """ :param board: current board on which we must make action :return: returns all child nodes """ parent_array = board.get_board_as_list() parent_coords = board.get_coords() result = [] for move in MOVES: new_coords = (parent_coords[0] + move[0], parent_coords[1] + move[1]) if verify_coords(new_coords): b = Board(parent_array) b.swap(parent_coords, new_coords) result.append(b) return result
def __init__(self, columns, rows, fps, countdown, interval, score_increment, level_increment, interval_increment, pygame_instance=None): self.COLUMNS = columns self.ROWS = rows self.FPS = fps self.COUNTDOWN = countdown self.INTERVAL = interval self.SCORE_INCREMENT = score_increment self.LEVEL_INCREMENT = level_increment self.INTERVAL_INCREMENT = interval_increment if pygame_instance is None: self.pygame = pygame else: self.pygame = pygame_instance self.sensehat = SenseHat() self.db = TinyDB('data/database.json') try: self.WIDTH = self.BLOCK_SIZE * self.COLUMNS + 150 self.HEIGHT = self.BLOCK_SIZE * self.ROWS self.BACKGROUND_GRID = [[ 8 if x % 2 == y % 2 else 0 for x in range(self.COLUMNS) ] for y in range(self.ROWS)] self.pygame.init() self.pygame.key.set_repeat(0, 0) self.pygame_font = self.pygame.font.Font( self.pygame.font.get_default_font(), 12) self.pygame_screen = self.pygame.display.set_mode( (self.WIDTH, self.HEIGHT), 0, 24) self.pygame.event.set_blocked(self.pygame.MOUSEMOTION) self.board = Board(self.COLUMNS, self.ROWS) self.__generate_snake() self.__generate_apple() except AttributeError: print("[Game][error] An error occurred initialising game")
def __init__(self, speed, players, num_players=2, debug=False): self.speed = speed self.players = players self.debug = debug self.move_ticks = speed.get_move_ticks() self.cooldown_ticks = speed.get_cooldown_ticks() self.players_ready = {i + 1: False for i in xrange(num_players)} self.board = Board.initial() self.active_moves = [] self.cooldowns = [] self.move_log = [] self.current_tick = 0 self.last_move_time = time.time() self.last_tick_time = time.time() self.started = False self.finished = 0 self.start_time = datetime.datetime.utcnow() self.last_capture_tick = 0 self.piece_to_move_seq_fn = { 'P': self._get_pawn_move_seq, 'N': self._get_knight_move_seq, 'B': self._get_bishop_move_seq, 'R': self._get_rook_move_seq, 'Q': self._get_queen_move_seq, 'K': self._get_king_move_seq, }
def replay_start(): data = json.loads(request.data) history_id = data['historyId'] print 'replay start', data game_history = db_service.get_game_history(history_id) if game_history is None: return json.dumps({ 'success': False, 'message': 'Replay does not exist.', }) # create game and add to game states replay = Replay.from_json_obj(game_history.replay) if replay.players[2].startswith('c'): level = int(replay.players[2][2:]) campaign_level = campaign.get_level(level) game = Game(Speed(replay.speed), replay.players, board=Board.from_str(campaign_level.board), is_campaign=True) else: game = Game(Speed(replay.speed), replay.players) for player in replay.players: game.mark_ready(player) game_id = generate_game_id() game_states[game_id] = GameState(game_id, game, {}, {}, replay) return json.dumps({ 'success': True, 'gameId': game_id, })
def time_test(): testBoard = Board.create_init_board() brain = Brain() testBoard.add_piece(Piece(Color.WHITE, Coordinate(1, 1))) testBoard.add_piece(Piece(Color.WHITE, Coordinate(2, 1))) testBoard.add_piece(Piece(Color.WHITE, Coordinate(3, 1))) testBoard.add_piece(Piece(Color.WHITE, Coordinate(14, 1))) testBoard.add_piece(Piece(Color.WHITE, Coordinate(6, 1))) testBoard.add_piece(Piece(Color.WHITE, Coordinate(7, 1))) testBoard.add_piece(Piece(Color.BLACK, Coordinate(1, 4))) testBoard.add_piece(Piece(Color.BLACK, Coordinate(2, 4))) testBoard.add_piece(Piece(Color.BLACK, Coordinate(3, 4))) testBoard.add_piece(Piece(Color.BLACK, Coordinate(5, 4))) testBoard.add_piece(Piece(Color.BLACK, Coordinate(6, 4))) testBoard.add_piece(Piece(Color.BLACK, Coordinate(7, 4))) """ ############################### # # # # # # # B B B B B B # # # # # # W W W W W # # # ############################### """ brain.make_move(testBoard)
def test_early(): testBoard = Board.create_init_board() brain = Brain() testBoard.add_piece(Piece(Color.WHITE, Coordinate(1, 1))) testBoard.add_piece(Piece(Color.WHITE, Coordinate(1, 2))) brain.make_move(testBoard)
def setup_new_game(self): self.board = Board() self.ai_player.set_board(self.board) self.game_board.set_board(self.board.get_cards()) self.side_panel.player_score = 0 self.side_panel.robot_score = 0 self.side_panel.update_score()
def reset(self): print("[Game][info] Resetting game") self.PAUSED = False self.GAMEOVER = False self.SCORE = 0 self.APPLES = 0 self.LEVEL = 1 self.SNAKE_MOVED = True self.board = Board(self.COLUMNS, self.ROWS) self.snake = None self.apple = None self.__generate_snake() self.__generate_apple() self.sensehat.clear() self.pygame.time.set_timer(pygame.USEREVENT + 1, 0) self.pygame.display.update()
class LocalSearch: def __init__(self, size: int): self.size = size self.optimum = Board(size) self.optimal_cost = self.optimum.cost() def search_step(self, optimum: Board): """ Step searches the new optimal neighbour in a greedy manner. The optimal neighbour is returned if there exists an improvement. Otherwise, None is returned. :param optimum: The board from which the neighbourhood will be checked. :return: The improved Board or None if there does not exist any. """ optimal_cost = optimum.cost() curr_optimum = optimum curr_cost = optimal_cost for neighbour in curr_optimum.neighbourhood(): if curr_optimum is None or curr_cost > neighbour.cost(): curr_optimum = neighbour curr_cost = neighbour.cost() if curr_cost < optimal_cost: return curr_optimum else: return None def search(self, n=10, retries=20): """ Attempts to find the optimal solution to the n-Queens problem using local search where the maximum number of retries is given. Each retry has a maximum of 'n' search steps. :param n: The maximum number of search steps for each retry. :param retries: The number of retries. :return: The optimum found by the local search algorithm. """ for retry in range(retries): curr_optimum = Board(self.size) for step in range(n): x = self.search_step(curr_optimum) if x is None: break curr_optimum = x if curr_optimum.cost() < self.optimal_cost: self.optimum = curr_optimum self.optimal_cost = curr_optimum.cost() if self.optimal_cost == 0: return self.optimum return self.optimum
def __init__(self, parent, options, dic='./dics/sowpods.txt'): Frame.__init__(self, parent, bg='azure') self.grid(row=0, column=0, sticky=S+N+E+W) self.dict = Dict(dic) self.bag = Bag() self.board = Board() self.set_variables() # There isn't a play_num key in the options, it is a game joined on lan if options.get('play_num', False): self.joined_lan = False self.resolve_options(options) else: self.joined_lan = True self.thread = threading.Thread(target=lh.join_lan_game, args=(options, self.queue)) self.thread.start() self.resolve_options(options) self.run()
def test_valid_coordinates(self): board = Board() self.assertTrue(board.valid_coordinate("A1")) self.assertTrue(board.valid_coordinate("A3")) self.assertTrue(board.valid_coordinate("D3")) self.assertFalse(board.valid_coordinate("Q7")) self.assertFalse(board.valid_coordinate("Coordinate")) self.assertFalse(board.valid_coordinate("1A"))
def solveAStart(self): """ Solve function, read the neighbours append the dist and moves to the queue Queue picks small distances and puzzle is solved """ startTime = time.time() board = Board(self.boardList, goalState=self.goalState, n=self.n) print("Start State .............") print(board) goal = Board(board.goalState, goalState=None, n=self.n) print("Goal State ..............") print(goal) queue = PriorityQueue() queue.put(board.getPriority(0)) i = 1 while not queue.empty(): board = queue.get()[2] if not board.isGoal(): for neighbour in board.getNeighbours(): if neighbour != board.previous: queue.put(neighbour.getPriority(i)) i += 1 else: self.analytics("A star", board.move, i, time.time() - startTime, board) return
def test_place_a_ship_horizontally(): board = Board(board_width, board_height) ship = Ship(3, 'horizontal') board.place_ship(ship, 2, 2) board.print() assert board.squares[0] == [False, False, False, False, False, False] assert board.squares[1] == [False, ship, ship, ship, False, False] assert board.squares[2] == [False, False, False, False, False, False]
def selection(self, board): """Start the MCTS process by selecting the next leaf node. This is done for as long as the specified budget (here: time) allows.""" self.board = board legal_cols = Board.valid_locations(board) leg_rows = [Board.where_it_lands(self.board, x) for x in legal_cols] legal_pos = [(r, c) for r, c in zip(leg_rows, legal_cols)] startTime = time.time() outtaTime = False self.cur_visits = np.zeros((6, 7), dtype=int) # n_j while not outtaTime: self.board = board # get UCT values for all legal_positions uct_values = [self.uct_value(self.values[x[0]][x[1]], self.N, self.cur_visits[x[0]][x[1]]) for x in legal_pos] # select move with maximum uct value select = legal_pos[np.argmax(uct_values)] self.expansion(child=select) playTime = time.time() - startTime outtaTime = (playTime > 1) self.cur_visits = np.zeros((6, 7), dtype=int) self.N = 0 # now that we have an updated value matrix, select most promising action # leg_mov_values = Estimated game theoretic value leg_mov_values = [self.values[x[0]][x[1]] for x in legal_pos] best_move = legal_cols[np.argmax(leg_mov_values)] return best_move
def classify_orbs(frame): """ classifies the orbs in a given BGR frame and returns a board object """ hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV_FULL) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) plus = cv2.imread( r'C:\Users\cuish\Documents\PersonalProjects\pad-auto\resources\plus.png', 0) kpp, desp = sift.detectAndCompute(plus, None) xstart, xend, ystart, yend, size = get_canvas_position(frame) data = [] for y in range(5): for x in range(6): ycor = int(y * size + ystart) xcor = int(x * size + xstart) cellhsv = hsv[ycor:ycor + size, xcor:xcor + size, slice(None)] cellgray = gray[ycor:ycor + size, xcor:xcor + size] # assign cell base value cut = crop_center_square(cellhsv, size / 3) avg = np.mean(cut[:, :, 0]) # print(x,y,avg) for k, v in ORB_DATA.items(): if v.huerange: lower, upper = v.huerange if lower < avg < upper: cellvalue = k break else: raise Exception("Unidentifiable Cell (%s, %s). Hue: %s" % (x, y, avg)) # determine cell + status kp2, des2 = sift.detectAndCompute(cellgray, None) matches = matcher.knnMatch(desp, trainDescriptors=des2, k=2) if count_matches(matches) > 10: cellvalue |= 0x10 data.append(cellvalue) assert len(data) == 30 piece_dic = {1: Fire, 2: Water, 3: Wood, 4: Light, 5: Dark, 6: Heart} piece_list = [piece_dic[n] for n in data] number_of_rows = 5 number_of_columns = 6 board = Board(piece_list, number_of_rows, number_of_columns) return board
def __init__(self): super(TestMod, self).__init__() self.add_bomb = False self.board = Board(self.config['board']['size']) x, y = self.board.get_size() for i in range(x): for j in range(y): Grid(i,j,self.board) self.pointer = Pointer(1,1,self.board) print "Press escape to quit" print "Use arrow keys to move" print "Enter to add a bomb" print "1 to add 100 bombs" print "r to remove all bombs"
def setup_method(self, method): self.b = Board() self.valid_pos = {'row': 0, 'col': 1} self.invalid_pos = {'row': 0, 'col': -5} self.color = 'red'
class Memory(object): def __init__(self): self.screen = pygame.display.set_mode((800, 600),1) pygame.display.set_caption("Memory v1.0") self.loader = Loader() self.game_board = GameBoard() self.side_panel = SidePanel() self.robot_mouse = RobotMouse() self.ai_player = AIPlayer(3) self.side_panel.ai_level = self.ai_player.level self.side_panel.update_stats() self.pair_snd = self.loader.load_sound("pair.wav") self.win_snd = self.loader.load_sound("win.wav") self.win_snd.set_volume(0.5) self.boom_snd = self.loader.load_sound("boom.wav") self.boom_snd.set_volume(0.3) self.stardust = StarDustAnim() self.starburst = StarBurstAnim() def setup_new_game(self): self.board = Board() self.ai_player.set_board(self.board) self.game_board.set_board(self.board.get_cards()) self.side_panel.player_score = 0 self.side_panel.robot_score = 0 self.side_panel.update_score() def select_card(self,card): self.board.select_card(card) self.game_board.touch_card(card) def main_loop(self): clock = pygame.time.Clock() SETUP_NEW_GAME = 0 PLAYER1_SELECT_FIRST = 10 PLAYER1_SELECT_SECOND = 11 PLAYER1_DONE = 12 PLAYER2_SELECT_FIRST = 50 PLAYER2_SELECT_SECOND = 51 PLAYER2_DONE = 52 ROBOT_SELECT_FIRST = 20 ROBOT_SELECT_FIRST_WAIT = 21 ROBOT_SELECT_SECOND = 30 ROBOT_SELECT_SECOND_WAIT = 31 ROBOT_DONE = 40 GAME_OVER = 98 GAME_OVER_WAIT = 99 START_SCREEN = 100 DELAY = 40 state_delay = 0 state = START_SCREEN next_player = 0 starburst_count = 0 shown_cards = [] mouse_over_card = Card(-1, False) while 1: clock.tick(30) mouse_clicked = False mouse_pos = (0,0) for event in pygame.event.get(): if event.type == QUIT: return elif event.type == KEYDOWN: if event.key == K_ESCAPE: return #elif event.key == K_F1: # self.side_panel.player_score =18 # self.side_panel.robot_score = 0 # state = GAME_OVER #elif event.key == K_F2: # self.side_panel.player_score = 0 # self.side_panel.robot_score = 18 # state = GAME_OVER #elif event.key == K_F3: # self.side_panel.player_score = 9 # self.side_panel.robot_score = 9 # state = GAME_OVER elif event.type == MOUSEBUTTONDOWN: #if event.button == 3: # self.starburst.add(event.pos) if event.button == 1: mouse_clicked = True mouse_pos = event.pos # === STATE HANDLER === is_select_event = False selected_card = Card(-1, False) if event.type == MOUSEMOTION: mouse_over_card.mouse_over = False c = self.game_board.location_to_card(event.pos) if c is not None: c.mouse_over = True mouse_over_card = c if state_delay > 0: state_delay -= 1 else: # --- NEW GAME --- if state == START_SCREEN and mouse_clicked: state = SETUP_NEW_GAME self.setup_new_game() self.game_board.goto_game() elif state == SETUP_NEW_GAME: if self.side_panel.x > 600: self.side_panel.x-=10 else: if next_player == 1: self.side_panel.show_robot(False,0,0) state = PLAYER2_SELECT_FIRST next_player = 0 else: self.side_panel.show_player1(False) state = PLAYER1_SELECT_FIRST next_player = 1 # --- PLAYER1 STATES --- elif state == PLAYER1_SELECT_FIRST and self.stardust.anim_done() and self.game_board.is_init_done() and mouse_clicked: c = self.game_board.location_to_card(mouse_pos) is_select_event = True selected_card = c if c and not c.selected: self.select_card(c) state = PLAYER1_SELECT_SECOND elif state == PLAYER1_SELECT_SECOND and mouse_clicked: c = self.game_board.location_to_card(mouse_pos) is_select_event = True selected_card = c if c and not c.selected: self.select_card(c) state = PLAYER1_DONE state_delay = DELAY elif state == PLAYER1_DONE: pair = self.board.end_of_turn() if pair: for p in pair: self.stardust.add(self.game_board.card_to_location(p)) self.side_panel.player1_score+=1 self.side_panel.update_score() state = PLAYER1_SELECT_FIRST self.pair_snd.play() else: self.side_panel.show_player2(False) state = PLAYER2_SELECT_FIRST if self.board.is_game_over(): state = GAME_OVER # --- PLAYER2 STATES --- elif state == PLAYER2_SELECT_FIRST and self.stardust.anim_done() and self.game_board.is_init_done() and mouse_clicked: c = self.game_board.location_to_card(mouse_pos) is_select_event = True selected_card = c if c and not c.selected: self.select_card(c) state = PLAYER2_SELECT_SECOND elif state == PLAYER2_SELECT_SECOND and mouse_clicked: c = self.game_board.location_to_card(mouse_pos) is_select_event = True selected_card = c if c and not c.selected: self.select_card(c) state = PLAYER2_DONE state_delay = DELAY elif state == PLAYER2_DONE: pair = self.board.end_of_turn() if pair: for p in pair: self.stardust.add(self.game_board.card_to_location(p)) self.side_panel.robot_score+=1 self.side_panel.update_score() state = PLAYER2_SELECT_FIRST self.pair_snd.play() else: self.side_panel.show_player1(False) state = PLAYER1_SELECT_FIRST if self.board.is_game_over(): state = GAME_OVER # --- GAME OVER --- elif state == GAME_OVER and self.stardust.anim_done(): r = self.side_panel.show_winner() self.win_snd.play() self.side_panel.games_stat+=1 if r == 1: self.side_panel.player_stat+=1 self.ai_player.you_lose() elif r == 2: self.side_panel.robot_stat+=1 self.ai_player.you_win() self.side_panel.ai_level = self.ai_player.level self.side_panel.update_stats() self.game_board.goto_gameover(r) state = GAME_OVER_WAIT starburst_count = 40 starburst_delay = 0 elif state == GAME_OVER_WAIT: if mouse_clicked: self.game_board.goto_game() self.setup_new_game() state = SETUP_NEW_GAME self.starburst.stop() else: if starburst_count: if starburst_delay == 0: starburst_count-=1 self.boom_snd.play() x = random.randint(50,550) y = random.randint(50,550) self.starburst.add((x,y)) starburst_delay = random.randint(15,30) else: starburst_delay -= 1 # === DRAWING === self.game_board.draw(self.screen) if is_select_event and not (selected_card in shown_cards): self.game_board.render_large_image(self.screen, selected_card) shown_cards.append(selected_card) if state != START_SCREEN: self.side_panel.draw(self.screen) self.robot_mouse.draw(self.screen) self.stardust.draw(self.screen) self.starburst.draw(self.screen) pygame.display.flip()