def play(self): self.b1 = Board(6, 7) self.p1 = players(1) self.a1 = AI(2) Board.print_board(self.b1) game_over = False while not game_over: if self.turn == 0: game_over = self.p1.make_move(self.b1) self.b1.print_board() if self.b1.winning_move(self.p1.piece): print("Player 1 wins") game_over = True else: col, minimax_score = AI.minimax(self.a1, self.b1, 5, -math.inf, math.inf, True) if self.b1.is_valid_location(col): row = self.b1.get_next_open_row(col) self.b1.drop_piece(row, col, self.a1.piece) if self.b1.winning_move(self.a1.piece): print("player 2 wins") game_over = True self.b1.print_board() self.update_turn()
def main(): if len(sys.argv) < 2: print "Please enter a host name." exit(1) ai = AI() socket = library.open_server_connection(sys.argv[1], "19000") if socket == -1: sys.stderr.write("Unable to connect to server\n") exit(1) if not library.serverLogin(socket, ai.username(), ai.password()): exit(1) if len(sys.argv) < 3: socket = library.createGame() else: socket = library.joinGame(int(sys.argv[2])) while library.networkLoop(socket, 0): if ai.startTurn(): library.endTurn() else: library.getStatus() #request the log file while library.networkLoop(socket, 0): pass exit(0)
def __init__(self, settings, screen, scoreboard): super().__init__() self.settings = settings self.screen = screen self.screen_rect = self.screen.get_rect() self.scoreboard = scoreboard self.__label = None self.__moving_up = None self.__moving_down = None self.__moving_left = None self.__moving_right = None self.paddles = None self.__is_ai = False self.ai = AI(self, settings) self.__score = 0 self.reset()
def __init__(self, threadID, name, monitor): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.monitor = monitor self.AI = AI()
def test_model_vs_random(self, n_games=100, size=10, display=False, model_path="models/trained.h5"): ai1 = AI(mode="NN", size=10, player=1, load=True, model_file=model_path) ai2 = AI(mode="random", size=10, player=2) nb_wins = 0 nb_losses = 0 nb_draws = 0 for i in range(n_games): winner = self.run_game(size=10, players=[ai1, ai2], save_positions=False) if winner == 1: nb_wins += 1 elif winner == 2: nb_losses += 1 else: nb_draws += 1 print( "Model won %i games, lost %i and drawn %i against random (out of %i games)" % (nb_wins, nb_losses, nb_draws, n_games))
def setup(grid): print("Insert Player 1 information:") # Get Player 1 type player1_type = get_player_type() print("Player 1 is ", player1_type) # Get Player 1 icon 'X' or 'O' player1_icon = get_player_icon() print("Player 1 is ", player1_icon) print("Insert Player 2 information:") # Get Player 2 type player2_type = get_player_type() print("Player 2 is ", player2_type) # Player 2 icon is opposite of Player 1 if player1_icon == 'X': player2_icon = 'O' else: player2_icon = 'X' print("Player 2 is ", player2_icon) if player1_type == 'Human': player.append(Player(player1_icon, grid)) else: player.append(AI(player1_icon, grid)) if player2_type == 'Human': player.append(Player(player2_icon, grid)) else: player.append(AI(player2_icon, grid))
def pve(turn=0): ai = AI(PLAYER_1, PLAYER_2) i = 0 game.__init__() print_game(game) while not game.check_winner(): i += 1 if i % 2 == turn: # TODO: Get AI turn # player = PLAYER_1 # move = move = ai.search(game) game.put_piece(move, PLAYER_1) print_game(game) print('\n', ai.pred) else: # Make player move while True: try: move = int(input('\n{} - Enter col:'.format(PLAYER_2))) - 1 except ValueError: continue except EOFError: import sys sys.exit() if game.put_piece(move, PLAYER_2): break print_game(game) print_ending(game)
class Regul(threading.Thread): def __init__(self, threadID, name, monitor): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.monitor = monitor self.AI = AI() def destroy(self): print(self.name, "Destroyed") self.run_r = False def run(self): print("Starting " + self.name) print("Press q to quit") self.run_r = True max_y, max_x = self.monitor.init_Regul() self.AI.init_AI(max_y, max_x) while (self.run_r & self.monitor.calibrated()): xPuck, yPuck, xPlayer, yPlayer = self.monitor.get_pos() set_y, set_x = self.AI.follow_puck(int(xPuck), int(yPuck), int(xPlayer), int(yPlayer)) self.monitor.regulate(set_y, set_x)
def __init__(self, x, y, direction): self.x = x self.y = y self.positions = [[x, y, direction]] self.AI = AI('yolov3.weights', 'yolov3.cfg', 0.7) self.tool = Manipulator() self.direction = direction
def __init__(self): self.board = ChessBoard() self.view = ChessView(self) self.view.showMsg("Red") self.view.draw_board(self.board) self.player_is_red = True self.ai = AI()
def __init__(self): self.goldenBank = GoldenBank("goldenballvalues.txt") self.distributionPanel = DistributionPanel() self.playerLyst = [User("user"), AI("com1"), AI("com2"), AI("com3")] self.binOrWinTable = BinOrWinTable() self.splitOrSteal = SplitOrSteal() self.theVote = TheVote()
def game_loop(screen, white_turn): board = Board(screen) ai_engine = AI() start = None game_over = False has_quit = False #LOOP while not game_over and not has_quit: #PROCESS EVENTS if white_turn: for event in pygame.event.get(): if event.type == pygame.QUIT: has_quit = True elif event.type == pygame.MOUSEBUTTONDOWN: x, y = pygame.mouse.get_pos() i, j = utils.chess_index(x, y) if board.is_white((i, j)) and white_turn: start = i, j elif start and board.make_move(start, (i, j)): game_over = board.board.is_game_over() start = None white_turn = not white_turn else: move = ai_engine.minimax(5, board, white_turn, -INFINITY, INFINITY) board.board.push(move[0]) white_turn = not white_turn #DRAW board.render_board() board.render_selections(start) board.render_pieces() pygame.display.flip()
def local_init(self): print(13) self.player_enter() self.player = Model(self,random.randint(0,1000),200,200,self.pSelect,self.is_online) self.player.skillChosen = self.skillChosen self.camera.player = self.player self.charList.append(self.player) self.player.playerName=self.playerName print(23) self.enemy = AI(self,random.randint(0,1000),700,200,2,self.is_online) self.enemy.playerName='pyq' self.enemy2 = AI(self,random.randint(0,1000),600,200,1,self.is_online) self.enemy2.playerName='hzs' self.enemy3 = AI(self,random.randint(0,1000),600,200,3,self.is_online) self.enemy3.playerName='zn' #self.player.enemy = self.enemy self.enemy.enemy = self.player self.enemy2.enemy = self.player self.enemy3.enemy = self.player self.charList.append(self.enemy) self.charList.append(self.enemy2) self.charList.append(self.enemy3) print(33)
def __init__(self): pygame.init() logo = pygame.image.load(str(BASE_DIR.joinpath('logo.png'))) pygame.display.set_icon(logo) self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), 0, 32) pygame.display.set_caption("BATTLESHIPS!") self.clock = pygame.time.Clock() menu_font = pygame.font.Font( 'DejaVuSans.ttf', 16) # default font can't display check mark self.gui = Gui(self.init, self.save, self.load, self.set_ai, menu_font) self.font = pygame.font.Font(None, 36) menu_offset = (0, self.gui.menus.rect.h) self.my_board = Board(BOARD_WIDTH, BOARD_HEIGHT, self.screen, menu_offset) self.crosshair = Crosshair(self.my_board, (0, 0), menu_offset) self.enemy_board = Board(BOARD_WIDTH, BOARD_HEIGHT, self.screen, (550, 25)) self.ai = AI(self.enemy_board) self.gui.update_ai_menu(self.ai.strength) self.textpos = pygame.Rect(10, 545, 50, 30) self.ship_images = {} for size in range(1, 6): self.ship_images[size] = load_image(f'ship{size}.bmp', 'gfx')
class Controller(): def __init__(self): self.sending_flag = True self.conf = {} self.network = None self.queue = Queue() self.world = World(self.queue) self.client = AI() self.argNames = ["AICHostIP", "AICHostPort", "AICToken", "AICRetryDelay"] self.argDefaults = ["127.0.0.1", 7099, "00000000000000000000000000000000", "1000"] def start(self): self.read_settings() self.network = Network(ip=self.conf[self.argNames[0]], port=self.conf[self.argNames[1]], token=self.conf[self.argNames[2]], message_handler=self.handle_message) self.network.connect() def run(): while self.sending_flag: event = self.queue.get() self.queue.task_done() message = { 'name': Event.EVENT, 'args': [{'type': event.type, 'args': event.args}] } self.network.send(message) Thread(target=run, daemon=True).start() def terminate(self): print("finished!") self.network.close() self.sending_flag = False def read_settings(self): if os.environ.get(self.argNames[0]) is None: for i in range(len(self.argNames)): self.conf[self.argNames[i]] = self.argDefaults[i] else: for i in range(len(self.argNames)): self.conf[self.argNames[i]] = os.environ.get(self.argNames[i]) def handle_message(self, message): if message[Constants.KEY_NAME] == Constants.MESSAGE_TYPE_INIT: self.world.handle_init_message(message) elif message[Constants.KEY_NAME] == Constants.MESSAGE_TYPE_TURN: self.world.handle_turn_message(message) self.do_turn() elif message[Constants.KEY_NAME] == Constants.MESSAGE_TYPE_SHUTDOWN: self.terminate() def do_turn(self): def run(): self.client.do_turn(self.world) Thread(target=run, daemon=True).start()
def __init__(self, settings_file): self.settings_file = settings_file self.sending_flag = True self.conf = {} self.network = None self.queue = Queue() self.model = Model(self.queue) self.client = AI()
def move(self,stiuation): player_ai = AI(stiuation) if(type(player_ai.decision()) == str): print(player_ai.decision()) else: move_x, move_y = player_ai.decision() self.position_x += move_x self.position_y += move_y
def getAlphaBetaMove(board, parser): import MoveNode as MoveNode depth = 1 AIagent = AI(board, True, depth) legalMoves = board.getAllMovesLegal(board.currentSide) bestMove = None moveTree = AIagent.generateMoveTree() legalBestMoves = AIagent.bestMovesWithMoveTree(moveTree) #conLegalMoves = AIagent.getAllMovesLegalConcurrent(board.currentSide) def alphaBetaMax(alpha, beta, depth): global bestMove value = -float(999999) #if (depth == 0 or board.isCheckmate or board.isStalemate): if (depth == 0): return (board.getPointValueOfSide(board.currentSide), ) random.shuffle(legalBestMoves) for move in legalBestMoves: random.shuffle(legalMoves) for m in legalMoves: random.shuffle(legalMoves) value = max(value, alphaBetaMin(alpha, beta, depth - 1)[0]) if (value >= beta): return beta, m if (value > alpha): alpha = value bestMove = m bestMove.notation = parser.notationForMove(bestMove) #return {'alpha': alpha, 'bestMove': bestMove} return alpha, bestMove #return bestMove def alphaBetaMin(alpha, beta, depth): global bestMove value = float(999999) #if (depth == 0 or board.isCheckmate or board.isStalemate): if (depth == 0): return (-board.getPointValueOfSide(board.currentSide), ) random.shuffle(legalBestMoves) for move in legalBestMoves: random.shuffle(legalMoves) for m in legalMoves: random.shuffle(legalMoves) value = min(value, alphaBetaMax(alpha, beta, depth - 1)[0]) if (value <= alpha): return alpha, m if (value < beta): beta = value bestMove = m bestMove.notation = parser.notationForMove(bestMove) #return {'beta': beta, 'bestMove': bestMove} return beta, bestMove #return bestMove score, action = alphaBetaMax(-999999, 999999, 3) return score, action
def createPlayers(mode): global playerOne global playerTwo if mode == 'Human vs AI': playerOne = Human('playerOne') playerTwo = AI('playerTwo') if mode == 'AI vs AI': playerOne = AI('playerOne') playerTwo = AI('playerTwo')
def main(): game = AI() prompt() while(True): # while EOG get_palyer_input() game.make_move() print_result()
def createPlayers(mode): global playerOne, playerTwo if mode == 'Human vs AI': playerOne = Human('playerOne') if mode == 'AI vs AI': playerOne = randomAI('playerOne') playerTwo = AI('playerTwo') playerOne.addDestCardToHand() playerTwo.addDestCardToHand()
def __init__(self): # On initie la grille et on met des strings vides pour symboliser aucun move en fait self.board_state = np.zeros([3, 3], dtype='str') self.previous_board_states = Stack() self.ai = AI() for i in range(len(self.board_state)): self.board_state[i] = " "
def __init__(self): self.sending_flag = True self.conf = {} self.network = None self.queue = Queue() self.world = World(self.queue) self.client = AI() self.argNames = ["AICHostIP", "AICHostPort", "AICToken", "AICRetryDelay"] self.argDefaults = ["127.0.0.1", 7099, "00000000000000000000000000000000", "1000"] self.turn_num = 0
class Bot(Player): def __init__(self, location, world, move_delay=settings.move_frames): super().__init__(location) self._bot = True self.actions = [] self.path = [] self.draw_path = [] self.collision_lines = [] self._grid = world.grid self.ai = AI(world.grid.neighbors, self.ai_callback, Bot.task_error_callback) self.goal = self.last_goal = None self._recompute = False self.move_delay = move_delay self.delay_count = 0 def handle_ai_task(self): recompute = (not self.goal == self.last_goal) or self._recompute if recompute: self._recompute = False self.end_move(flush_queue=True) find_path = False if self.goal and (not self.moving or recompute): find_path = True if find_path: self.ai.pathfind(Node(self.loc.to_grid()), Node(self.goal)) def update(self): super().update() self.handle_ai_task() if self.delay_count > 0: self.delay_count -= 1 def ai_callback(self, result): self.actions = [] self.path = [] for r in result: self.actions.append(r[0]) self.path.append(r[1]) self.draw_path = self.path.copy() if result: self.move(self.actions[0]) for move in self.actions[1:]: self.moves.push(move) def scan_callback(self, results): self.collision_lines = [] for collidable, collision_line in results: if line_length(collision_line[0], collision_line[len(collision_line) - 1]) < 700: self.collision_lines.append(collision_line) @staticmethod def task_error_callback(err): print('Task failed') print_exception(type(err), err, None)
def init(self): if (self.player1IsHuman): self.player1 = Player(Game.SIDE_X) else: self.player1 = AI(Game.SIDE_X) if (self.player2IsHuman): self.player2 = Player(Game.SIDE_O) else: self.player2 = AI(Game.SIDE_O)
def __reset_game_data(self): """重置游戏数据方法。 清空棋盘,并设置目前玩家为玩家 1,胜者为空。 """ self.__board = [[PlayerEnum.NO_PLAYER] * BOARD_WIDTH for _ in range(BOARD_HEIGHT)] self.__player = PlayerEnum.PLAYER_ONE, PlayerEnum.PLAYER_TWO self.__winner = None self.__steps = [] self.__ai = AI(self.__player)
def __init__(self): pygame.init() pygame.display.set_caption("new! mine sweeper") self.screen = pygame.display.set_mode((545, 625)) self.img = pygame.image.load("img.png") self.ai = AI() self.board = [[[0, 0] for _ in range(16)] for _ in range(16)] self.start = None self.loop = True self.turn = 0 self.numberOfFlag = 40 self.numberOfMine = 40
def handle_turn_message(self, currentState): self.client = AI() game = Game() game.initGameConfig(self.gameConfig) game.setCurrentState(currentState) self.client.game = game (message, value, direction) = self.client.turn() if direction is not None: self.send_direction_message(direction) if message is not None and value is not None: self.send_chat_message(message, value) self.send_end_message()
def __init__(self): self.board = Board() self.ai = AI(AI_ID, self.board) self.timeout_turn = 0 self.timeout_match = 0 self.max_memory = 0 self.time_left = 0 self.game_type = 0 self.rule = 1 self.evaluate = "" self.folder = "" self.__end = False
class Controller(): def __init__(self, settings_file): self.settings_file = settings_file self.sending_flag = True self.conf = {} self.network = None self.queue = Queue() self.model = Model(self.queue) self.client = AI() def start(self): self.read_settings() self.network = Network(ip=self.conf[Constants.CONFIG_KEY_IP], port=self.conf[Constants.CONFIG_KEY_PORT], token=self.conf[Constants.CONFIG_KEY_TOKEN], message_handler=self.handle_message) self.network.connect() def run(): while self.sending_flag: event = self.queue.get() self.queue.task_done() message = { Constants.KEY_NAME: Constants.MESSAGE_TYPE_EVENT, Constants.KEY_ARGS: [event] } self.network.send(message) Thread(target=run, daemon=True).start() def terminate(self): print("finished!") self.network.close() self.sending_flag = False def read_settings(self): with open(self.settings_file) as file: self.conf = json.loads(file.read()) def handle_message(self, message): if message[Constants.KEY_NAME] == Constants.MESSAGE_TYPE_INIT: self.model.handle_init_message(message) elif message[Constants.KEY_NAME] == Constants.MESSAGE_TYPE_TURN: self.model.handle_turn_message(message) self.do_turn() elif message[Constants.KEY_NAME] == Constants.MESSAGE_TYPE_SHUTDOWN: self.terminate() def do_turn(self): def run(): self.client.do_turn(self.model.world) Thread(target=run, daemon=True).start()
def play(self): """ Purpose: Runs the game until someone has won Pre-Conditions: N/A Return: N/A """ while True: if self.victory() == 1: print(self.board) print( "\n\n/////////////////\n Player 1 Wins!! \n/////////////////\n" ) break if self.victory() == 2: print(self.board) print( "\n\n/////////////////\n Player 2 Wins!! \n/////////////////\n" ) break if self.ai2 is not None and self.player == 2: print(self.board) self = AI.move(3, self, 2) self.player = 1 if self.ai1 is not None and self.player == 1: print(self.board) self = AI.move(3, self, 1) self.player = 2 if self.ai1 is None or self.ai2 is None: self.select_move() if len(AI.searchList) > 0: print("Average nodes searched: " + str((sum(AI.searchList) / len(AI.searchList)))) print("Average time taken: " + str((sum(AI.timeList) / len(AI.timeList)))) print("Total move time for AI: " + str(sum(AI.timeList))) print("Average nodes searched: " + str((sum(AI.searchListWithoutAlpha) / len(AI.searchListWithoutAlpha)))) print("Average time taken: " + str((sum(AI.timeListWithoutAlpha) / len(AI.timeListWithoutAlpha)))) print("Total move time for AI: " + str(sum(AI.timeListWithoutAlpha)))
def run(self): startPlayer = self.view.inputStartPlayer() computerPlayer = 'X' if startPlayer == 2 else 'O' ai = AI(computerPlayer, self.board) while self.evaluation.winner() == None and not self.evaluation.isTie(): self.view.displayBoard() if self.board.getPlayer() == computerPlayer: ai.makeMove() else: move = self.view.inputMove() self.board.move(move) self.view.displayBoard() self.__finish(computerPlayer)
def __init__(self): self.sending_flag = True self.conf = {} self.network = None self.queue = Queue() self.world = World(self.queue) self.client = AI() self.argNames = ["AICHostIP", "AICHostPort", "AICToken", "AICRetryDelay"] self.argDefaults = ["127.0.0.1", 7099, "00000000000000000000000000000000", "1000"]
def start(self): # for car in cars: # nextAction = AI.nextStep(car.id, state) # state = state.getStateByAction(car.id, nextAction) # Drawer.draw(state) # Start currCarIdx = 0 nextAction = AI.nextStep(currCarIdx, state) state = state.getStateByAction(currCarIdx, nextAction) Drawer.draw(state) while(not state.isGoal()): nextCarIdx = self.getNextCarIdx(currCarIdx) nextAction = AI.nextStep(currCarIdx, state) state = state.getStateByAction(currCarIdx, nextAction) Drawer.draw(state)
def main(): if len(sys.argv) < 2: print "Please enter a host name." exit(1) connection = library.createConnection(); ai = AI(connection) success = library.serverConnect(connection, sys.argv[1], "19000") if not success: sys.stderr.write("Unable to connect to server\n") exit(1) if not library.serverLogin(connection, ai.username(), ai.password()): exit(1) if len(sys.argv) < 3: library.createGame(connection) else: library.joinGame(connection, int(sys.argv[2])) while library.networkLoop(connection): if ai.startTurn(): library.endTurn(connection) else: library.getStatus(connection) #Grab the end game state library.networkLoop(connection) #request the log file library.networkLoop(connection) ai.end() exit(0)
def on_enter(self): ''' Sets the game ''' # You can only enter the game from the intro self.deck = Deck() self.cards = self.deck.drawGuarantee(numberofcards=12) for i in range(len(self.scores_of_players)): self.scores_of_players[i] = 0 self.ai = AI(self.directory) self.aiScore = 0 self.game.active = True self.active = True self.newRound() self.t0 = datetime.datetime.now()
class BrickController(): def __init__(self,model,ai=None): if ai is None: self.ai = AI(model) else: self.ai = ai def dec_learn_rate(self,learn_dec): self.ai.ALPHA = max(0,self.ai.ALPHA-learn_dec) def save_ai(self,file_name = "trained_ai.p"): p.dump(self.ai, open(file_name,"wb")) def ai_update_model(self,model): #self.ai.follow_ball(model) self.ai.make_qlearn_move(model) def controller_update_model(self,model): keys = pygame.key.get_pressed() if keys[pygame.K_LEFT]: model.paddle.left -= 5 if model.paddle.left < 0: model.paddle.left = 0 if keys[pygame.K_RIGHT]: model.paddle.left += 5 if model.paddle.left > MAX_PADDLE_X: model.paddle.left = MAX_PADDLE_X if keys[pygame.K_SPACE] and model.state == STATE_BALL_IN_PADDLE: model.ball_vel = [5,-5] model.state = STATE_PLAYING elif keys[pygame.K_RETURN] and (model.state == STATE_GAME_OVER or model.state == STATE_WON): self.init_game()
def __init__(self): pygame.init() logo = pygame.image.load(os.path.join(BASE_DIR, 'logo.png')) pygame.display.set_icon(logo) self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), 0, 32) pygame.display.set_caption("BATTLESHIPS!") self.clock = pygame.time.Clock() self.ai = AI() menu_font = pygame.font.Font('DejaVuSans.ttf', 16) # default font can't display check mark self.gui = Gui(self.init, self.set_ai, menu_font) self.gui.update_ai_menu(self.ai.strength) self.font = pygame.font.Font(None, 36) menu_offset = (0, self.gui.menus.rect.h) self.my_board = Board(BOARD_WIDTH, BOARD_HEIGHT, self.screen, menu_offset) self.crosshair = Crosshair(self.my_board, (0, 0), menu_offset) self.enemy_board = Board(BOARD_WIDTH, BOARD_HEIGHT, self.screen, (550, 25)) self.textpos = pygame.Rect(10, 545, 50, 30) self.ship_images = {} for size in range(1, 6): image = load_image('ship{size}.bmp'.format(size=size), 'gfx') self.ship_images[size] = image
def main(): computer = AI(board, board_coordinates) print ("Welcome to Tic Tac Toe! Player is 'X', CPU is 'O'.") computer.print_board() game_won = False while game_won is False: if computer.check_board_for_winner(): break print ("Player's turn...") computer.get_free_spots() player_move = int(input("Enter your field number: ")) GPS = computer.coordinates[player_move] while computer.board[GPS[0]][GPS[1]] != ".": player_move = int(input("Enter valid field number: ")) GPS = computer.coordinates[player_move] computer.board[GPS[0]][GPS[1]] = "X" computer.available_spots.remove(computer.coordinates[player_move]) computer.print_board() print ("CPU's turn ...") computer.get_free_spots() computer.move() computer.print_board() game_won = computer.check_board_for_winner() if computer.get_free_spots() == [] and game_won is False: print("Round draw.") break
def __init__(self): self.ai = AI() self.ai.drawStatus()
resolution = resolutions[resolution] fullscreen = enableFullscreen[fullscreen] background = "Backgrounds/" + backgrounds[background] screen = Screen(resolution, background, fullscreen, caption = "Call of Cthulhu LCG") try: # MAKE UP SOME PLAYERS AND CARDS # Players P1 = AI('Frrmack') P2 = AI('Boris') # P1 = Player('Frrmack') # P2 = Player('Boris') # Decks Deck1 = Deck('Random Deck 1') Deck2 = Deck('Random Deck 2') for n in range(50): # Cardtype = [Character, Event, Support][poisson(0.5) % 3] # redcard = Cardtype( 'Red Card %i'%(n+1), randomize=True ) # bluecard = Cardtype( 'Blue Card %i'%(n+1), randomize=True ) cardfile = rnd.choice(glob.glob('Cards/*.card')) card = parseCardFile(cardfile) Deck1.add(card)
class TestAI(unittest.TestCase): def setUp(self): self.testAI = AI([[".", ".", "."], [".", ".", "."], [".", ".", "."]], {1: (0, 0), 2: (0, 1), 3: (0, 2), 4: (1, 0), 5: (1, 1), 6: (1, 2), 7: (2, 0), 8: (2, 1), 9: (2, 2)}) def test_init(self): self.assertEqual(self.testAI.board, [[".", ".", "."], [".", ".", "."], [".", ".", "."]]) self.assertEqual(self.testAI.coordinates, {1: (0, 0), 2: (0, 1), 3: (0, 2), 4: (1, 0), 5: (1, 1), 6: (1, 2), 7: (2, 0), 8: (2, 1), 9: (2, 2)}) def test_free_spots(self): self.testAI.board = [["X", "X", "."], ["X", ".", "O"], ["O", ".", "O"]] result = self.testAI.get_free_spots() self.assertEqual(result, [(0, 2), (1, 1), (2, 1)]) def test_move_with_one_spot_available(self): self.testAI.board = [["X", "X", "O"], ["O", ".", "X"], ["O", "X", "O"]] self.testAI.move() self.assertEqual(self.testAI.board, [["X", "X", "O"], ["O", "O", "X"], ["O", "X", "O"]]) self.assertEqual(self.testAI.get_free_spots(), []) def test_check_rows_of_matrix_correct(self): self.testAI.board = [["X", "X", "X"], ["O", ".", "X"], ["O", "X", "O"]] result = self.testAI.check_rows_of_matrix(self.testAI.board) self.assertTrue(result) def test_check_cols_of_matrix_correct(self): self.testAI.board = [["X", "O", "X"], ["X", ".", "X"], ["X", "X", "O"]] transposed = zip(*self.testAI.board) result = self.testAI.check_rows_of_matrix(transposed) self.assertTrue(result) def test_check_cols_of_matrix_incorrect(self): self.testAI.board = [["X", "O", "X"], ["O", "X", "O"], ["X", "O", "X"]] result = self.testAI.check_rows_of_matrix(self.testAI.board) self.assertFalse(result) def test_diagonals_correct(self): self.testAI.board = [["X", "O", "X"], ["O", "X", "O"], ["X", "O", "X"]] result = self.testAI.check_diagonals(self.testAI.board) self.assertTrue(result) def test_diagonals_incorrect(self): self.testAI.board = [["X", "X", "X"], ["X", "O", "O"], ["X", "O", "O"]] result = self.testAI.check_diagonals(self.testAI.board) self.assertFalse(result) def test_check_board_fully_correct(self): self.testAI.board = [["X", "O", "X"], ["X", ".", "X"], ["X", "X", "O"]] result = self.testAI.check_board_for_winner() self.assertTrue(result) def test_check_board_fully_incorrect(self): self.testAI.board = [[".", ".", "."], [".", ".", "."], [".", ".", "."]] result = self.testAI.check_board_for_winner() self.assertFalse(result)
class Game: def __init__(self): pygame.init() logo = pygame.image.load(os.path.join(BASE_DIR, 'logo.png')) pygame.display.set_icon(logo) self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), 0, 32) pygame.display.set_caption("BATTLESHIPS!") self.clock = pygame.time.Clock() self.ai = AI() menu_font = pygame.font.Font('DejaVuSans.ttf', 16) # default font can't display check mark self.gui = Gui(self.init, self.set_ai, menu_font) self.gui.update_ai_menu(self.ai.strength) self.font = pygame.font.Font(None, 36) menu_offset = (0, self.gui.menus.rect.h) self.my_board = Board(BOARD_WIDTH, BOARD_HEIGHT, self.screen, menu_offset) self.crosshair = Crosshair(self.my_board, (0, 0), menu_offset) self.enemy_board = Board(BOARD_WIDTH, BOARD_HEIGHT, self.screen, (550, 25)) self.textpos = pygame.Rect(10, 545, 50, 30) self.ship_images = {} for size in range(1, 6): image = load_image('ship{size}.bmp'.format(size=size), 'gfx') self.ship_images[size] = image def init(self, log): shipCountBySize = {5: 1, 4: 1, 3: 2, 2: 2, 1: 3} self.won = None self.players_turn = True self.my_board.reset_fields() self.enemy_board.reset_fields() self.my_ships = place_ships(self.enemy_board, shipCountBySize) self.enemy_ships = place_ships(self.my_board, shipCountBySize, False) self.remaining_ships = shipCountBySize if log: self.gui.clear_log() self.gui.log("Welcome to Battleships!") def set_ai(self, level): self.ai.strength = level self.gui.log('AI level set to {l}'.format(l=level.name)) self.gui.update_ai_menu(level) def switch_turns(self, value=None): if value is None: self.players_turn = not self.players_turn else: self.players_turn = value def log_shot(self, ship): who = 'You have' if self.players_turn else 'Your opponent has' color = MY_COLOR if self.players_turn else ENEMY_COLOR if ship is None: self.gui.log('{who} missed'.format(who=who), color) return action = 'sunk' if ship.discovered else 'hit' whose = 'your' if ship.is_mine else 'the enemy' self.gui.log('{who} {action} {whose} ship!'.format(who=who, action=action, whose=whose), color) if ship.discovered and not ship.is_mine: self.remaining_ships[ship.size] -= 1 def check_game_end(self): if self.won is not None: return if all(ship.discovered for ship in self.my_ships): self.won = False self.gui.log('YOU LOST!', ENEMY_COLOR) elif all(ship.discovered for ship in self.enemy_ships): self.won = True self.gui.log('YOU WON!', MY_COLOR) # TODO: popup message? def show_remaining_ships(self): offset = 60 for size, count in self.remaining_ships.items(): text_pos = pygame.Rect(offset, 545, 50, 30) amount = self.font.render('{c}x'.format(c=count), 1, TEXT_COLOR) self.screen.blit(amount, text_pos) offset += 30 ship_size = size * FIELD_SIZE ship_pos = pygame.Rect(offset, 535, ship_size, FIELD_SIZE) image = self.ship_images[size] self.screen.blit(image, ship_pos) offset += ship_size + 20 def show_coords(self, coords): self.screen.blit(coords, self.textpos) def run(self): self.init(False) # The main game loop while True: # Limit frame speed to 50 FPS time_passed = self.clock.tick(50) if self.won is None and not self.players_turn: hit, ship = self.ai.shoot(self.enemy_board) self.log_shot(ship) if ship is not None: self.check_game_end() continue self.switch_turns() for event in pygame.event.get(): if self.gui.is_active() or self.gui.is_gui_click(event): # pass it on to gui self.gui.handle(event) elif event.type == pygame.QUIT: sys.exit() elif event.type == KEYDOWN: # TODO: keyboard shortcuts & navigation for menu if event.key == K_ESCAPE: sys.exit() elif event.key in [K_UP, K_DOWN, K_RIGHT, K_LEFT]: self.crosshair.move(event.key) elif event.key == K_RETURN and self.won is None: hit, ship = self.my_board.shoot(self.crosshair.position) if hit is None: break self.log_shot(ship) self.check_game_end() self.switch_turns(hit) elif event.key == K_SPACE: self.my_board.uncover_all() self.check_game_end() elif event.type == MOUSEBUTTONDOWN and event.button == 1 and self.won is None: # left click hit, ship = self.my_board.uncoverPixels(event.pos) if hit is None: break self.log_shot(ship) self.check_game_end() self.switch_turns(hit) elif event.type == MOUSEMOTION: self.crosshair.moveTo(event.pos) coords = self.font.render(self.crosshair.coords(), 1, TEXT_COLOR) # Redraw the background self.screen.fill(BG_COLOR) self.my_board.display() self.enemy_board.display() self.crosshair.display() self.show_remaining_ships() self.show_coords(coords) self.gui.paint() pygame.display.flip()
def __init__(self,model,ai=None): if ai is None: self.ai = AI(model) else: self.ai = ai
class GamePlayScreen(Screen): numberofsets = NumericProperty(0) restart = ObjectProperty() screenManager = ObjectProperty() aiScore = NumericProperty() aiActivated = BooleanProperty() directory = StringProperty('') hintActivated = BooleanProperty(False) number_of_players = NumericProperty(1) name_of_players = ListProperty(['', '', '', '']) scores_of_players = ListProperty([0, 0, 0, 0]) cards = ListProperty() displayHintTimer = NumericProperty(5) aiPlayed = BooleanProperty(False) active = BooleanProperty(False) def __init__(self, *args, **kwargs): super(GamePlayScreen, self).__init__(*args, **kwargs) self.rotator = Rotator() Clock.schedule_once(self.post_init,0) def post_init(self,*args): self.buttons = self.ids.cards_layout.children for i in range(12): self.buttons[i].bind(on_press=self.checkIfSetOnBoard) # Dealing with multiplayer ### def select_player_popup(self, *args): '''called when three cards are selected''' popup = SelectPlayersPopup(self) popup.open() def on_pre_leave(self): self.endscreen = self.game.get_screen('end') self.endscreen.aiScore = self.aiScore self.active = False def unselectAll(self): ''' Unselect all the toggle buttons ''' for button in self.buttons: button.state = 'normal' def on_enter(self): ''' Sets the game ''' # You can only enter the game from the intro self.deck = Deck() self.cards = self.deck.drawGuarantee(numberofcards=12) for i in range(len(self.scores_of_players)): self.scores_of_players[i] = 0 self.ai = AI(self.directory) self.aiScore = 0 self.game.active = True self.active = True self.newRound() self.t0 = datetime.datetime.now() def goToSettings(self): Clock.unschedule(self.AIplay) Clock.unschedule(self.aiMoves) App.get_running_app().open_settings() def newRound(self): ''' What should be done at the begining of every round ''' self.stopRotation() self.updateGrid() self.setUpHint() self.unselectAll() self.setUpAI() def foundCorrect(self, down, *args): ''' Called once a shugou is found ''' self.aiUpdates() if self.aiPlayed: self.aiScore += 1 self.aiPlayed = False else: if self.number_of_players > 1: self.select_player_popup() else: self.scores_of_players[0] += 1 selectedcards = {self.cards[i] for i in down} try: newcards = self.deck.drawGuarantee( othercards=set(self.cards) ^ selectedcards, numberofcards=3) except ValueError: # no more shugous available self.game.current = 'end' return for index, i in enumerate(down): self.cards[i] = newcards[index] self.newRound() def checkIfSetOnBoard(self, obj): '''Called when a button is pressed, checks if there is a set. If there is one, then refill the display cards''' down = self.selected() if not len(down) == 3: return if Deck.checkSet(self.cards[down[0]], self.cards[down[1]], self.cards[down[2]]): if App.get_running_app().music.soundActivated: # Taken from: http://www.freesound.org/people/lukechalaudio/sounds/151568/ sound = SoundLoader.load("music/" + "151568__lukechalaudio__user-interface-generic" + ".wav") sound.loop = False sound.play() # We send the selection in case the player unselects a card before # self.foundCorrect is found self.stopRotation() Clock.schedule_once(lambda arg: self.foundCorrect(down=down), 2) else: # The cards were not a set self.unselectAll() def updateGrid(self): for i, card in enumerate(self.cards): self.buttons[i].card = card self.buttons[i].state = 'normal' self.setUpHint() self.t0 = datetime.datetime.now() if self.aiActivated: self.setUpAI() def aiUpdates(self): timeDifference = datetime.datetime.now() - self.t0 if self.aiPlayed: self.ai.time += 10 self.ai.updateRatingsAI( self.cards, self.aiCards, timeDifference) else: self.ai.time -= 7 if self.ai.time < 5: self.ai.time = 5 down = self.selected() # Crashes now, no idea why # selected = self.cards[down[0]], \ # self.cards[down[1]],\ # self.cards[down[2]] # self.ai.updateRatingsHuman( # self.cards, selected, timeDifference) def stopRotation(self): self.rotator.end_rotate() def selected(self): '''Returns the indices of all the selected ToggleButton''' down = [] for index, button in enumerate(self.buttons): if button.state == 'down': down.append(index) return down def buttonFromCard(self, card): ''' Returns the instance of the button that contains the given card''' for button in self.buttons: if button.card == card: return button def selectCards(self, cards): ''' selects the given cards if they are in the given cards ''' for index, button in enumerate(self.buttons): if self.cards[index] in cards: button.state = 'down' # Functions related to the AIhint ### def setUpAI(self): Clock.unschedule(self.AIplay) if self.aiActivated and self.active: (time, self.aiCards) = self.ai.suggestion(self.cards) Clock.schedule_once(self.AIplay, time) def AIplay(self, *arg): ''' The AI plays a turn ''' for index, card in enumerate(self.cards): if card in self.aiCards: self.buttons[index].state = 'down' else: self.buttons[index].state = 'normal' # Basic AI animation. Clock.schedule_once(self.aiMoves, 0.1) self.aiPlayed = True def aiMoves(self, *arg): self.checkIfSetOnBoard(None) # Functions related to displaying hint ### def on_displayHintTimer(self, obj, value): self.setUpHint() def setUpHint(self): ''' unschedule any current hint and loads up the next one if appropriate''' # Need to remove any previous call or else it might be activated too # quickly Clock.unschedule(self.displayHint) Clock.unschedule(self.displayHintSecond) # After some time in seconds show a hint if self.hintActivated and self.active: self.hint = Deck.hint(self.cards) Clock.schedule_once(self.displayHint, self.displayHintTimer) def on_hintActivated(self, obj, is_activated): if not is_activated: self.stopRotation() def displayHint(self, *arg): ''' Displays the first card in the hint and sets-up the display of the second card in the hint''' if self.selected() == []: # no cards have been selected # displays on the first card in a hint buttonToRotate = self.buttonFromCard(self.hint[0]) self.rotator.rotate_this(buttonToRotate) Clock.schedule_once(self.displayHintSecond, self.displayHintTimer) else: # if the player has a card selected, try calling it again later self.setUpHint() def displayHintSecond(self, *arg): ''' Displays the second of two cards in a hint''' selectedcards = self.selected() buttonToRotate = self.buttonFromCard(self.hint[1]) self.rotator.rotate_this(buttonToRotate) # Functions to handling the game play screen def selected(self): '''Returns the indices of all the selected ToggleButton''' down = [] for index, button in enumerate(self.buttons): if button.state == 'down': down.append(index) return down def stopClocks(self): Clock.unschedule(self.AIplay) Clock.unschedule(self.displayHint) Clock.unschedule(self.displayHintSecond)
def getAiMove(): validMoves = findValids(False) coords = AI.getMove(validMoves, game_difficulty, board) __getMove(coords[0], coords[1], False)
def setUp(self): self.testAI = AI([[".", ".", "."], [".", ".", "."], [".", ".", "."]], {1: (0, 0), 2: (0, 1), 3: (0, 2), 4: (1, 0), 5: (1, 1), 6: (1, 2), 7: (2, 0), 8: (2, 1), 9: (2, 2)})
{'nbUnits':5,'owner':0} ]) mainBoard.addEdges([ (0,1,2000), (0,2,2000), (3,4,2000), (3,5,2000), (6,7,2000), (6,8,2000), (1,9,3000), (3,9,3000), (4,9,3000), (5,9,3000), (7,9,3000), (8,9,3000)]); ai=AI(mainBoard); print(mainBoard); print(ai.evalBoard(0)) print(ai.evalBoard(1)) print(ai.evalBoard(2)) print(ai.evalBoardByNodeWeight(1,True)) root=Tk() root.title="Test" app=Display(mainBoard,master=root) app.mainloop() root.destroy()