def guess(gameid, pos_1, pos_2, pos_3, pos_4): guess = { "pos_1": int(pos_1), "pos_2": int(pos_2), "pos_3": int(pos_3), "pos_4": int(pos_4) } game = Game() feedback = game.guess(gameid, guess) return json.dumps(feedback)
def handle(self, handler_input): print('PlayGameHandler ----------------------') attrs_manager = handler_input.attributes_manager request_attrs = attrs_manager.request_attributes session_attrs = attrs_manager.session_attributes is_first_question = int(session_attrs.get('current_question', 0)) <= 1 key = 'PLAY_GAME_FIRST_QUESTION' if is_first_question else 'PLAY_GAME_MID_GAME' message = utils._( key, {'current_question': session_attrs['current_question']}) request_attrs['output_speech'].append(message['output_speech']) Game.ask_question(handler_input, False) return handler_input.response_builder.response
def __init__(self): """ Initialize the GUI """ # Initialize the game self.game = Game() # Initialize the GUI screen pygame.init() self.screen = pygame.display.set_mode(GUI_SIZE) pygame.display.update() # Define font to display main headers self.font = pygame.font.SysFont('monospace', 75) # Define font to display sub-headings self.options_font = pygame.font.SysFont('monospace', 50)
def main(): try: accounts_names = [] valid_cookies_index = get_valid_cookies(len(os.listdir('cookies'))) for i in valid_cookies_index: logging.info(f'Запуск %s аккаунта', i) ctx = mp.get_context('spawn') queue = ctx.Queue() p = ctx.Process(target=Game().run, kwargs=dict(index=i, queue=queue)) p.name = str(i) p.start() user_account = queue.get() logging.info('Аккаунт %s - %s', i, user_account) accounts_names.append(user_account) logging.info('Запуск аккаунтов окончен.') with open('WAXParser/accounts.txt', 'w') as f: for account in accounts_names: f.write(account + '\n') while True: time.sleep(5000) except KeyboardInterrupt: # завершение всех старых процессов мозиллы os.system('taskkill /f /im firefox.exe') logging.info("\nЗавершение работы бота...") os.system('cls' if os.name == 'nt' else 'clear') sys.exit()
def handle(self, handler_input): print('DontKnowNextHandler ----------------------') attrs_manager = handler_input.attributes_manager request_attrs = attrs_manager.request_attributes session_attrs = attrs_manager.session_attributes session_attrs['current_question'] = int( session_attrs.get('current_question', 0)) + 1 is_last_question = session_attrs['current_question'] > settings.GAME[ 'questions_per_game'] key = 'SKIP_LAST' if is_last_question else 'SKIP' message = utils._(f"PLAY_GAME_{key}_QUESTION") request_attrs['output_speech'].append( f"{message['output_speech']}<break time='1s'/>") Game.ask_question(handler_input, False) return handler_input.response_builder.response
def main(): pygame.init() win = pygame.display.set_mode((RES, RES)) surface = pygame.Surface((RES, RES)) surface = surface.convert() clock = pygame.time.Clock() game = Game() while True: clock.tick(120) if game.update_canvas() == "QUIT": pygame.quit() sys.exit() handle_events(game) drawgrid(surface, game) win.blit(surface, (0, 0)) pygame.display.update()
def __init__(self, height=11, width=11, snake_cnt=4, health_dec=1, game_cnt=1): self.height = height self.width = width self.snake_cnt = snake_cnt self.health_dec = health_dec self.game_cnt = game_cnt self.games = { ID: Game(ID, height, width, snake_cnt, health_dec) for ID in range(game_cnt) }
def __init__(self, height=11, width=11, snake_cnt=4, health_dec=1, game_cnt=1): self.height = height self.width = width self.snake_cnt = snake_cnt self.health_dec = health_dec self.game_cnt = game_cnt self.games = { ID: Game(ID, height, width, snake_cnt, health_dec) for ID in range(game_cnt) } # log self.wall_collision = 0 self.body_collision = 0 self.head_collision = 0 self.starvation = 0 self.food_eaten = 0 self.game_length = 0
async def start(self, ctx): # Initial start game command game = Game(self.bot, ctx.author.id) self.games[ctx.author.id] = game await self.startui(ctx, game, 1)
def history(gameid): game = Game() history = game.history(gameid) return json.dumps(history)
width = 11 snake_cnt = 4 competeEps = 128 file_name1 = input("\nEnter the model 1 name:\n") file_name2 = input("\nEnter the model 2 name:\n") nnet1 = AlphaNNet(model="models/" + file_name1 + ".h5") nnet2 = AlphaNNet(model="models/" + file_name2 + ".h5") Alice = Agent(nnet1) Bob = Agent(nnet2) win = 0 draw = 0 t0 = time() for _ in range(competeEps): g = Game(height, width, snake_cnt) winner_id = g.run(Alice, Bob, 1) if winner_id is None: draw += 1 elif winner_id < 1: win += 1 print("1v3 WR of", file_name1, win / (competeEps), "DR =", draw / (competeEps)) print("Competing time", time() - t0) win = 0 draw = 0 t0 = time() for _ in range(competeEps): g = Game(height, width, snake_cnt) winner_id = g.run(Bob, Alice, 1) if winner_id is None:
def newgame(userid): game = Game() new_game_id = game.new_game(userid) return json.dumps(new_game_id)
def handle(self, handler_input): print('EndGameHandler ----------------------') Game.end_game(handler_input, False) return handler_input.response_builder.response
def train_with_agent(self, trainer=0): """ Method to train the game robot using Q-learning :param trainer: type of agent to train the game robot :return: nothing """ player_win_data, agent_win_data, player_moves, agent_moves = [0], [0], [0], [0] draw = [0] x = list(range(0, (100 * ITERATIONS) + 1, 100)) learning_player = QPlayer(epsilon=1.0) if trainer == 1: trained_player = QPlayer(token=0, mem_location='memory/memory1.npy') elif trainer == 2: trained_player = MiniMaxPlayer(token=0) else: trained_player = RandomPlayer(token=0) for i in range(ITERATIONS): print(i) learning_player.save_memory() if trainer == 1: trained_player.save_memory('memory/memory1.npy') player_moves[-1] = player_moves[-1] / ITERATIONS agent_moves[-1] = agent_moves[-1] / ITERATIONS player_win_data.append(0) agent_win_data.append(0) player_moves.append(0) agent_moves.append(0) draw.append(0) for j in range(ITERATIONS): prev_move = None, None player = choice((Q_ROBOT, RANDOM_ROBOT)) reward = REWARD_NOTHING reward1 = REWARD_NOTHING # Initialize the game self.game = Game() game_status = False current_board = self.game.current_state possible_moves = self.game.get_valid_locations(current_board) learning_player.train(possible_moves, reward, learning_player.token, self.game) if trainer == 1: trained_player.train(possible_moves, reward1, trained_player.token, self.game) elif trainer == 2: trained_player.depth = MINI_MAX_DEPTH while not game_status: for event in pygame.event.get(): if event.type == pygame.QUIT: exit() if player == Q_ROBOT: move = learning_player.get_optimal_move(current_board, possible_moves) self.game.add_player_token(move[0], move[1], learning_player.token) player_moves[-1] += 1 else: if trainer == 1: move = trained_player.get_optimal_move(current_board, possible_moves) elif trainer == 2: trained_player.depth = MINI_MAX_DEPTH move = trained_player.mini_max(deepcopy(self.game), prev_move, (learning_player.token, trained_player.token), -float('inf'), float('inf'), True)[0] else: move = trained_player.make_move(possible_moves) self.game.add_player_token(move[0], move[1], trained_player.token) agent_moves[-1] += 1 self.game.update_current_state(self.game.board) if self.game.is_winning_move(move[0], move[1], learning_player.token): game_status = True reward, reward1 = REWARD_WIN, REWARD_LOSS player_win_data[-1] += 1 elif self.game.is_winning_move(move[0], move[1], trained_player.token): game_status = True reward, reward1 = REWARD_LOSS, REWARD_WIN agent_win_data[-1] += 1 elif self.game.is_draw(): game_status = True reward, reward1 = REWARD_DRAW, REWARD_DRAW draw[-1] += 1 # Update player turn player = 3 - player # Update previous mode prev_move = move # Train the Q-learning players current_board = self.game.current_state possible_moves = self.game.get_valid_locations(current_board) learning_player.train(possible_moves, reward, learning_player.token, self.game) if trainer == 1: trained_player.train(possible_moves, reward1, trained_player.token, self.game) if game_status: if learning_player.exploration_chance > learning_player.epsilon_min: learning_player.exploration_chance *= learning_player.epsilon_decay # Take average of moves of the last iterations player_moves[-1] = player_moves[-1] / ITERATIONS agent_moves[-1] = agent_moves[-1] / ITERATIONS # PLot the graphs plt.figure(1) plt.title('Winning rate over games') plt.xlabel('No. of games') plt.ylabel('Average winning rate') plt.plot(x, player_win_data, color='orange', label='Q-Learning Player') plt.plot(x, agent_win_data, color='blue', label='Trained Agent') plt.legend() plt.show() plt.figure(2) plt.title('Moves over games') plt.xlabel('No. of games') plt.ylabel('Average moves') plt.plot(x, player_moves, color='orange', label='Q-Learning Player') plt.plot(x, agent_moves, color='blue', label='Trained Agent') plt.legend() plt.show()
class GameGUI: """ A class that represents the GUI of the game """ def __init__(self): """ Initialize the GUI """ # Initialize the game self.game = Game() # Initialize the GUI screen pygame.init() self.screen = pygame.display.set_mode(GUI_SIZE) pygame.display.update() # Define font to display main headers self.font = pygame.font.SysFont('monospace', 75) # Define font to display sub-headings self.options_font = pygame.font.SysFont('monospace', 50) def draw_main_menu(self): """ Draw main menu with different playing modes of the game :return: nothing """ pygame.draw.rect(self.screen, BLACK, (0, 0, GUI_SIZE[0], GUI_SIZE[1])) title = self.font.render(GAME_NAME, True, WHITE) font_size = self.font.size(GAME_NAME) self.screen.blit(title, ((GUI_SIZE[0] - font_size[0]) // 2, 150)) # Display multi-player option on main menu multi_player = self.options_font.render(GAME_MODES[0], True, WHITE) font_size = self.options_font.size(GAME_MODES[0]) corner = (GUI_SIZE[0] - font_size[0]) // 2, 300 self.screen.blit(multi_player, corner) self.rect_multi_player = multi_player.get_rect(topleft=corner) # Display play with computer option on main menu play_computer = self.options_font.render(GAME_MODES[1], True, WHITE) font_size = self.options_font.size(GAME_MODES[1]) corner = (GUI_SIZE[0] - font_size[0]) // 2, 400 self.screen.blit(play_computer, corner) self.rect_play_computer = play_computer.get_rect(topleft=corner) # Update the GUI screen pygame.display.update() def draw_board(self): """ Draw the empty configuration of the game :return: nothing """ # Draw rectangle to represent the board area where coins go in pygame.draw.rect(self.screen, BLACK, (0, 0, GUI_SIZE[0], CELL_SIZE)) # Draw rectangle to represent the board area where coins go in pygame.draw.rect(self.screen, BLUE, (0, CELL_SIZE, GUI_SIZE[0], GUI_SIZE[1] - CELL_SIZE)) # Draw circles to represent dots in the game for i in range(BOARD_SIZE[0]): for j in range(BOARD_SIZE[1]): # Get center of the next circle to be drawn on the GUI center = (j * CELL_SIZE + (CELL_SIZE // 2)), ((i + 1) * CELL_SIZE + (CELL_SIZE // 2)) # Draw the circle on the GUI pygame.draw.circle(self.screen, BLACK, center, RADIUS) # Update GUI pygame.display.update() def main_menu(self): """ Method to implement the logic behind the menu :return: mode of the game the user wants to play """ main_menu = True play_game = -1 self.draw_main_menu() while main_menu: for event in pygame.event.get(): if event.type == pygame.MOUSEBUTTONUP: position = pygame.mouse.get_pos() if self.rect_multi_player.collidepoint(position): main_menu = False play_game = 0 elif self.rect_play_computer.collidepoint(position): main_menu = False play_game = 1 if event.type == pygame.QUIT: exit() return play_game def run_game(self, game_mode, train=False, train_mode=0): """ Function to check for events occurring inside the GUI screen Executes entire functioning of the game :param game_mode: mode of the game, i.e., multi-player or single-player :param train: set true is you want to train the robot :param train_mode: type of agent to train with :return: nothing """ if game_mode == 0: self.run_multi_player() else: if train: self.train_with_agent(trainer=train_mode) else: self.run_single_player() def run_single_player(self, game_status=False): q_player = QPlayer(epsilon=0.01) player = choice((HUMAN_PLAYER, Q_ROBOT)) reward = REWARD_NOTHING current_board = self.game.current_state possible_moves = self.game.get_valid_locations(current_board) q_player.train(possible_moves, reward, player, self.game) while not game_status: if not player: for event in pygame.event.get(): if event.type == pygame.QUIT: exit() elif event.type == pygame.MOUSEMOTION: pygame.draw.rect(self.screen, BLACK, (0, 0, GUI_SIZE[1], CELL_SIZE)) col_index = int(event.pos[0] / CELL_SIZE) center = ((col_index * CELL_SIZE) + (CELL_SIZE // 2)), (CELL_SIZE // 2) pygame.draw.circle(self.screen, RED, center, RADIUS) elif event.type == pygame.MOUSEBUTTONUP: pygame.draw.rect(self.screen, BLACK, (0, 0, GUI_SIZE[1], CELL_SIZE)) col_index = int(event.pos[0] / CELL_SIZE) row_index = self.game.get_open_row(col_index, self.game.current_state) if row_index != -1: center = (((col_index * CELL_SIZE) + (CELL_SIZE // 2)), (((BOARD_SIZE[0] - row_index) * CELL_SIZE) + (CELL_SIZE // 2))) self.game.add_player_token(row_index, col_index, player) self.game.update_current_state(self.game.board) pygame.draw.circle(self.screen, RED, center, RADIUS) if self.game.is_winning_move(row_index, col_index, player): label = self.font.render('Player ' + str(player + 1) + ' Wins!', True, RED) self.screen.blit(label, (40, 10)) reward = REWARD_LOSS game_status = True if self.game.is_draw(): self.screen.blit('GAME HAS TIED', True, WHITE) reward = REWARD_DRAW game_status = True # Update turn of player player = (player + 1) % 2 else: move = q_player.get_optimal_move(current_board, possible_moves) pygame.draw.rect(self.screen, BLACK, (0, 0, GUI_SIZE[1], CELL_SIZE)) center = ((move[1] * CELL_SIZE) + (CELL_SIZE // 2)), (CELL_SIZE // 2) pygame.draw.circle(self.screen, YELLOW, center, RADIUS) # Update GUI and wait for some time pygame.display.update() pygame.time.wait(500) # Get center of the token location on the board and draw a circle there center = (((move[1] * CELL_SIZE) + (CELL_SIZE // 2)), (((BOARD_SIZE[0] - move[0]) * CELL_SIZE) + (CELL_SIZE // 2))) pygame.draw.circle(self.screen, YELLOW, center, RADIUS) self.game.add_player_token(move[0], move[1], player) self.game.update_current_state(self.game.board) if self.game.is_winning_move(move[0], move[1], player): label = self.font.render('Computer Wins!', True, YELLOW) self.screen.blit(label, (40, 10)) reward = REWARD_WIN game_status = True if self.game.is_draw(): reward = REWARD_DRAW game_status = True player = (player + 1) % 2 # Update GUI pygame.display.update() # Train the computer player current_board = self.game.current_state possible_moves = self.game.get_valid_locations(current_board) q_player.train(possible_moves, reward, player, self.game) if game_status: q_player.save_memory() pygame.time.wait(5000) def run_multi_player(self, game_status=False): """ Method to run multi-player (2 players') mode :param game_status: set false to start the game :return: nothing """ player = choice((HUMAN_PLAYER, HUMAN_PLAYER + 1)) while not game_status: for event in pygame.event.get(): if event.type == pygame.QUIT: exit() elif event.type == pygame.MOUSEMOTION: pygame.draw.rect(self.screen, BLACK, (0, 0, GUI_SIZE[1], CELL_SIZE)) col_index = int(event.pos[0] / CELL_SIZE) center = ((col_index * CELL_SIZE) + (CELL_SIZE // 2)), (CELL_SIZE // 2) if player: pygame.draw.circle(self.screen, YELLOW, center, RADIUS) else: pygame.draw.circle(self.screen, RED, center, RADIUS) elif event.type == pygame.MOUSEBUTTONUP: pygame.draw.rect(self.screen, BLACK, (0, 0, GUI_SIZE[1], CELL_SIZE)) col_index = int(event.pos[0] / CELL_SIZE) row_index = self.game.get_open_row(col_index, self.game.current_state) if row_index != -1: center = (((col_index * CELL_SIZE) + (CELL_SIZE // 2)), (((BOARD_SIZE[0] - row_index) * CELL_SIZE) + (CELL_SIZE // 2))) self.game.add_player_token(row_index, col_index, player) if player: pygame.draw.circle(self.screen, YELLOW, center, RADIUS) else: pygame.draw.circle(self.screen, RED, center, RADIUS) if self.game.is_winning_move(row_index, col_index, player): if player: label = self.font.render('Player ' + str(player + 1) + ' Wins!', True, YELLOW) else: label = self.font.render('Player ' + str(player + 1) + ' Wins!', True, RED) self.screen.blit(label, (40, 10)) game_status = True if self.game.is_draw(): self.screen.blit('GAME HAS TIED', True, WHITE) game_status = True # Update turn of player player = (player + 1) % 2 # Update GUI pygame.display.update() if game_status: pygame.time.wait(3000) def train_with_agent(self, trainer=0): """ Method to train the game robot using Q-learning :param trainer: type of agent to train the game robot :return: nothing """ player_win_data, agent_win_data, player_moves, agent_moves = [0], [0], [0], [0] draw = [0] x = list(range(0, (100 * ITERATIONS) + 1, 100)) learning_player = QPlayer(epsilon=1.0) if trainer == 1: trained_player = QPlayer(token=0, mem_location='memory/memory1.npy') elif trainer == 2: trained_player = MiniMaxPlayer(token=0) else: trained_player = RandomPlayer(token=0) for i in range(ITERATIONS): print(i) learning_player.save_memory() if trainer == 1: trained_player.save_memory('memory/memory1.npy') player_moves[-1] = player_moves[-1] / ITERATIONS agent_moves[-1] = agent_moves[-1] / ITERATIONS player_win_data.append(0) agent_win_data.append(0) player_moves.append(0) agent_moves.append(0) draw.append(0) for j in range(ITERATIONS): prev_move = None, None player = choice((Q_ROBOT, RANDOM_ROBOT)) reward = REWARD_NOTHING reward1 = REWARD_NOTHING # Initialize the game self.game = Game() game_status = False current_board = self.game.current_state possible_moves = self.game.get_valid_locations(current_board) learning_player.train(possible_moves, reward, learning_player.token, self.game) if trainer == 1: trained_player.train(possible_moves, reward1, trained_player.token, self.game) elif trainer == 2: trained_player.depth = MINI_MAX_DEPTH while not game_status: for event in pygame.event.get(): if event.type == pygame.QUIT: exit() if player == Q_ROBOT: move = learning_player.get_optimal_move(current_board, possible_moves) self.game.add_player_token(move[0], move[1], learning_player.token) player_moves[-1] += 1 else: if trainer == 1: move = trained_player.get_optimal_move(current_board, possible_moves) elif trainer == 2: trained_player.depth = MINI_MAX_DEPTH move = trained_player.mini_max(deepcopy(self.game), prev_move, (learning_player.token, trained_player.token), -float('inf'), float('inf'), True)[0] else: move = trained_player.make_move(possible_moves) self.game.add_player_token(move[0], move[1], trained_player.token) agent_moves[-1] += 1 self.game.update_current_state(self.game.board) if self.game.is_winning_move(move[0], move[1], learning_player.token): game_status = True reward, reward1 = REWARD_WIN, REWARD_LOSS player_win_data[-1] += 1 elif self.game.is_winning_move(move[0], move[1], trained_player.token): game_status = True reward, reward1 = REWARD_LOSS, REWARD_WIN agent_win_data[-1] += 1 elif self.game.is_draw(): game_status = True reward, reward1 = REWARD_DRAW, REWARD_DRAW draw[-1] += 1 # Update player turn player = 3 - player # Update previous mode prev_move = move # Train the Q-learning players current_board = self.game.current_state possible_moves = self.game.get_valid_locations(current_board) learning_player.train(possible_moves, reward, learning_player.token, self.game) if trainer == 1: trained_player.train(possible_moves, reward1, trained_player.token, self.game) if game_status: if learning_player.exploration_chance > learning_player.epsilon_min: learning_player.exploration_chance *= learning_player.epsilon_decay # Take average of moves of the last iterations player_moves[-1] = player_moves[-1] / ITERATIONS agent_moves[-1] = agent_moves[-1] / ITERATIONS # PLot the graphs plt.figure(1) plt.title('Winning rate over games') plt.xlabel('No. of games') plt.ylabel('Average winning rate') plt.plot(x, player_win_data, color='orange', label='Q-Learning Player') plt.plot(x, agent_win_data, color='blue', label='Trained Agent') plt.legend() plt.show() plt.figure(2) plt.title('Moves over games') plt.xlabel('No. of games') plt.ylabel('Average moves') plt.plot(x, player_moves, color='orange', label='Q-Learning Player') plt.plot(x, agent_moves, color='blue', label='Trained Agent') plt.legend() plt.show()
from utils.alphaNNet import AlphaNNet from utils.agent import Agent from utils.game import Game from player import Player height = 11 width = 11 snake_cnt = 4 competeEps = 3 file_name = input("\nEnter the model name:\n") net = AlphaNNet(model="models/" + file_name + ".h5") net.v_net.summary() agent = Agent(net) f = open("replay.rep", 'w') f.write('') f.close() print("Running games...") for _ in range(competeEps): g = Game(height, width, snake_cnt) g.run(agent, show=True) n = input("\nHit Enter to watch replay") Player().main()
def handle(self, handler_input): print('GameEventHandler ----------------------') Game.handle_game_input_event(handler_input) return handler_input.response_builder.response
def handle(self, handler_input): print('YesHandler ----------------------') Game.ask_question(handler_input, False) return handler_input.response_builder.response
from flask import Flask, redirect, url_for from flask.helpers import flash from flask.templating import render_template from utils.game import Game app = Flask(__name__) game = Game() app.config['SECRET_KEY'] = 'dattebayo!' @app.route('/') def home_page(): return render_template('__home_page.html') @app.route('/game') def rps_game(): if (game.is_in_progress): if (game.winner == 'Bot'): flash('Opps! The Bot Got The Point', category='fail') elif (game.winner == 'Draw'): flash('Both Are Same! ', category='yellow') else: flash('Good! You Got The Point', category='success') game.winner = None game.is_in_progress = False return render_template('__game.html', choosed=game.started,
def main(): game = Game(BLACK, RES) game.run()
def handle(self, handler_input): print('AnswerHandler ----------------------') Game.answer_question(handler_input) return handler_input.response_builder.response
# importer charger notre bannière banner = pygame.image.load('assets/banner.png') banner = pygame.transform.scale(banner, (500, 500)) banner_rect = banner.get_rect() banner_rect.x = math.ceil(screen.get_width() / 4) # importer charger notre bouton pour lancer la partie play_button = pygame.image.load('assets/button.png') play_button = pygame.transform.scale(play_button, (400, 150)) play_button_rect = play_button.get_rect() play_button_rect.x = math.ceil(screen.get_width() / 3.33) play_button_rect.y = math.ceil(screen.get_height() / 2) # charger le jeux game = Game() # Le jeux running = True # Boucle tant que cette condition est vrai while running: # Appliquer la fenetre du jeux screen.blit(background, (0, 0)) # Verifier si notre jeux a commencer ou non if game.is_playing: # Déclencher les instructions de la partie game.update(screen) # Vérifier si notre jeux n'a pas commencer