def play_game(player1: Agent, player2: Agent) -> int: """ Agent1 plays first, agent2 plays second :param player1: an AI agent :param player2: an AI agent :returns: the winner; 1 = agent1, 2 = agent2, 0 = tie """ data = GameData() board = data.game_board while True: col = player1.get_move(data) row = board.get_next_open_row(col) board.drop_piece(row, col, 1) if board.winning_move(1, row, col): return 1 data.turn += 1 data.turn = data.turn % 2 col = player2.get_move(data) row = board.get_next_open_row(col) board.drop_piece(row, col, 2) if board.winning_move(2, row, col): return 2 if board.tie_move(): return 0
def _load_cache(self): with open(CACHE_FILE, "r", encoding="utf-8") as cache_file: logging.debug( f"data_cache.CacheData._load_cache: Loading cache from {CACHE_FILE}." ) data: dict[str, Any] = json.load(cache_file) new_data = dict() for k, game_data in data.items(): parsed_data: GameData = GameData(game_data) if parsed_data.expiration_date > datetime.now().timestamp(): new_data[k] = parsed_data new_data[k].subs = list( map(lambda sub: GameData.DiscountData(sub), data[k]["subs"])) self.data = new_data
def draw(self, game_data: GameData): """ Draws the game state, including the board and the pieces. :param game_data: All of the data associated with the game. """ if game_data.action == "undo": filled_circle( self.screen, game_data.last_move_row, game_data.last_move_col, self.game_data.radius, black, ) aacircle( self.screen, game_data.last_move_row, game_data.last_move_col, self.game_data.radius, black, ) self.draw_black_coin( game_data.last_move_col * self.game_data.sq_size + 5, self.game_data.height - (game_data.last_move_row * self.game_data.sq_size + self.game_data.sq_size - 5), ) game_data.game_board.print_board() game_data.action = None self.draw_board(game_data.game_board)
def parseMessage(self, msg, client): print("parsing message: {} from {}".format(msg, client.address)) if msg == "create_lobby": lobbyID = len(self.lobbies) print("{} created new lobby: {}".format(client.address, lobbyID)) self.lobbies.append( Lobby(lobbyID, GameData(), client, self.serverSocket)) self.sendMessage("Lobby created", client) return None if msg.__contains__("join_lobby_"): lobbyID = int(msg[msg.index("lobby_") + 6:]) if len(self.lobbies) > lobbyID: lobby = self.lobbies[lobbyID] lobby.join(client) self.sendMessage("Lobby joined", client) else: self.sendMessage("Lobby doesn't exist", client) return None if msg.__contains__("lID_"): # lobby specific package and parse lobbyID first tmp = msg[msg.index("lID_") + 4:] lobbyID = int(tmp[:tmp.index("_")]) if len(self.lobbies) > lobbyID: # redirect package to responsible lobby self.lobbies[lobbyID].receivePackage(tmp[tmp.index("_") + 1:], client)
def __init__(self): self.levels = [Level01, Level02] pygame.init() pygame.display.set_caption("Blast !") self.clock = pygame.time.Clock() self.screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT), 0, 32) self.game_data = GameData(self.screen) self.scene = Intro() self.scene.start() self.start_main_loop()
def startgame(): data = GameData() screen = pygame.display.set_mode(data.size) game = ConnectGame(data, GameRenderer(screen, data)) game.print_board() game.draw() pygame.display.update() pygame.time.wait(1000) # Processes mouse and keyboard events, dispatching events to the event bus. # The events are handled by the ConnectGame and GameRenderer classes. while not game.game_data.game_over: for event in pygame.event.get(): if event.type == pygame.QUIT: game.quit() if event.type == pygame.MOUSEMOTION: bus.emit("mouse:hover", game.renderer, MouseHoverEvent(event.pos[0])) pygame.display.update() if event.type == pygame.MOUSEBUTTONDOWN: bus.emit("mouse:click", game, MouseClickEvent(event.pos[0])) if event.type == KEYDOWN: if event.key == pygame.K_z: mods: int = pygame.key.get_mods() if mods & pygame.KMOD_CTRL: bus.emit("game:undo", game) game.update() game.draw()
def get_data(self): self.games = self.sc.textFile( '/home/jjj/Documents/GitHub/nfl_mongodb/json/games') self.games = self.games.map(GameData().get_data) # remove empty elements self.games = self.games.filter(lambda x: x) self.games.cache() self.data = self.games.collect()
def main(): GameData(SCREEN_TITLE) # SpriteCache() GameData.data['player_level'] = 1 GameData.data['player_xp'] = 0 window = arcade.Window(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE) sound_manager = SoundManager(window) loading_view = menu_views.LoadingMenuView(window, sound_manager) window.show_view(loading_view) arcade.run()
def play_game(player1: Agent, player2: Agent) -> int: """ Agent1 plays first, agent2 plays second :param player1: an AI agent :param player2: an AI agent :returns: the winner; 1 = agent1, 2 = agent2, 0 = tie """ data = GameData() board = data.game_board time_p1 = time_p2 = 0 while True: start = time.process_time() col = player1.get_move(data) time_p1 += time.process_time() - start row = board.get_next_open_row(col) if not isinstance(row, int): #TODO - shouldn't happen print("------------ Shouldn't happen: row:",row,", col:", col) board.print_board() return 0 data.last_move_row.append(row) data.last_move_col.append(col) board.drop_piece(row, col, 1) if board.winning_move(1, row, col): return 1, time_p1, time_p2 data.turn += 1 data.turn = data.turn % 2 start = time.process_time() col = player2.get_move(data) time_p2 += time.process_time() - start row = board.get_next_open_row(col) data.last_move_row.append(row) data.last_move_col.append(col) board.drop_piece(row, col, 2) if board.winning_move(2, row, col): return 2, time_p1, time_p2 if board.tie_move(): return 0, time_p1, time_p2
def __init__(self): self.server_port = 0 self.server_ip = NETWORK_ADDR self.server_socket = None self.selector = selectors.DefaultSelector() self.udp_broadcast_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.udp_broadcast_socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) self.broadcast_thread = None self.run_broadcast = True self.broadcast_iterations = 0 self.init_server_socket() self.offer = Offer(self.server_port) self.on_game = False self.init_groups_data() self.game_data = GameData()
def evaluate(): if args.player1 == HUMAN or args.player1 == HUMAN: raise Exception("Both players need to be AI") p1 = getAgent(args.player1) p2 = getAgent(args.player2) #compare_agents(agent1: Agent, agent2: Agent, n=5, alternate=True, print_progress=True) data = GameData() game = ConnectGame(data, GameRenderer(screen, data)) res = game.compare_agents(p1, p2, n=12, alternate=True, print_progress=True) print("res:", res)
def increase_xp(self, xp: int): leveled_up_bool = True self.current_xp += xp while leveled_up_bool: if self.current_xp >= XP_TO_NEXT_LEVEL_LIST[self.current_level - 1]: self.current_xp -= XP_TO_NEXT_LEVEL_LIST[self.current_level - 1] self.current_level += 1 self.max_hp = math.ceil( (self.current_level + 9) * 1.05**(self.current_level - 1)) self.current_hp = self.max_hp self.max_damage = 1 + (self.current_level - 1) self.attack_speed = 0.5 + (1.5 * self.current_level / 100) self.defense_level = self.current_level self.attack_level = self.current_level self.game_view.player_level_up() else: leveled_up_bool = False GameData.data['player_level'] = self.current_level GameData.data['player_xp'] = self.current_xp GameData.save_data()
def __init__(self): """Initializes the control unit and the game itself. Sets variables like window position, size, and initializes the GUI class""" self.FPS = 60 self.clock = pygame.time.Clock() self.state = GameState.MainMenu self.running = False self.screen_dimensions = (1000, 1000) os.environ['SDL_VIDEO_WINDOW_POS'] = "0,30" pygame.init() self.screen = pygame.display.set_mode(self.screen_dimensions) program_icon = pygame.image.load(res.ICON_LOOP) pygame.display.set_icon(program_icon) pygame.display.set_caption("Indefinite Loop") self.game_data = GameData("game_data.json") self.gui = GUI(self.screen, self.game_data) self.map = Map(self.screen, self.game_data) self.sound = SoundManager(self.game_data)
def main(): pygame.init() screen = pygame.display.set_mode(GameData().size) pygame.display.set_caption("Connect Four | Mayank Singh") message_display("CONNECT FOUR!!", white, 350, 150, 75, screen) message_display("HAVE FUN!", (23, 196, 243), 350, 300, 75, screen) running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False def button(msg, x, y, w, h, ic, ac, action=None): mouse = pygame.mouse.get_pos() click = pygame.mouse.get_pressed() if x + w > mouse[0] > x and y + h > mouse[1] > y: pygame.draw.rect(screen, ac, (x, y, w, h)) if click[0] == 1 and action is not None: action() else: pygame.draw.rect(screen, ic, (x, y, w, h)) small_text = pygame.font.SysFont("monospace", 30) text_surf, text_rect = text_objects(msg, small_text, white) text_rect.center = ((x + (w / 2)), (y + (h / 2))) screen.blit(text_surf, text_rect) button("2 PLAYERS", 125, 450, 170, 50, white, white, start_player_vs_player) button("2 PLAYERS", 127, 452, 166, 46, black, black, start_player_vs_player) # button("AI", 300, 450, 100, 50, white, white, start_player_vs_ai) # button("AI", 302, 452, 96, 46, black, black, start_player_vs_ai) button("COMPUTER", 125, 510, 170, 50, white, white, start_player_vs_ai) button("AI", 127, 512, 166, 46, black, black, start_player_vs_ai) button("QUIT", 500, 450, 100, 50, white, white, quit) button("QUIT", 502, 452, 96, 46, black, black, quit) pygame.display.update()
def start() -> None: while True: has_next = True page = 0 while has_next: r: Response = requests.get( f"{settings.wishlist_url()}/?p={page}&v=2") wishlist: dict[str, Any] = r.json() if r.status_code == 200 and wishlist: for data in wishlist.values(): expiration: float = ( datetime.now() + timedelta(settings.expiration_days)).timestamp() game_data: GameData = GameData(data, expiration) if game_data.has_discount( settings.min_discount) and game_data not in cache: notification_queue.put(game_data) else: has_next = False page += 1 time.sleep(settings.page_delay) time.sleep(settings.get_request_interval())
def __init__(self, challenger, oppositer, placement_rule, action_rule, ending_rule, board_size, board_info, obj_num, problem): self.board = np.zeros((board_size, board_size), dtype='i') self.board_info = board_info self.board_size = board_size self.board_record = '' # self.board = board_info self.check_turn = 'challenger' self.challenger = challenger self.opposite = oppositer self.game_data = GameData(placement_rule, action_rule, ending_rule, board_size, board_info, obj_num, problem) self.placement_rule = PlacementRule() self.action_rule = ActionRule() self.ending_rule = EndingRule() self.execution = Execution() self.placement_record = '' self.limit_time = 2000 self.error_msg = None
def start(): agent1 = MinimaxAgent() # red agent2 = RandomAgent() # yellow delay = 0.5 data = GameData() screen = pygame.display.set_mode(data.size) game = ConnectGame(data, GameRenderer(screen, data)) game.print_board() game.draw() pygame.display.update() pygame.time.wait(10) agent1_turn = 0 # Processes mouse and keyboard events, dispatching events to the event bus. # The events are handled by the ConnectGame and GameRenderer classes. while not game.game_data.game_over: for event in pygame.event.get(): if event.type == pygame.QUIT: game.quit() sleep(delay) if data.turn == agent1_turn and not game.game_data.game_over: game.make_movement(agent1.get_move(data)) game.update() game.draw() else: game.make_movement(agent2.get_move(data)) game.update() game.draw() game.update() game.draw()
def set_up_game(*, easy_aim: bool, easy_move: bool, easy_warp: bool, torpedo_warning: bool, crash_warning: bool, three_d_movment: bool, ship_name: str, captain_name: str, scenario: Scenerio, difficulty: type[BaseAi], allied_ai: type[BaseAi]): game_data = GameData(subsecs_x=CONFIG_OBJECT.sector_width, subsecs_y=CONFIG_OBJECT.sector_height, subsec_size_x=CONFIG_OBJECT.subsector_width, subsec_size_y=CONFIG_OBJECT.subsector_height, easy_aim=easy_aim, easy_move=easy_move, three_d_movment=three_d_movment, easy_warp=easy_warp, torpedo_warning=torpedo_warning, crash_warning=crash_warning, current_datetime=scenario.create_date_time(), starting_stardate=stardate( scenario.create_date_time()), ending_stardate=stardate(scenario.enddate), scenerio=scenario, difficulty=difficulty, alliled_ai=allied_ai) engine = Engine(filename="", player=game_data.player, easy_aim=easy_aim, easy_navigation=easy_move, easy_warp=easy_warp, torpedo_warning=torpedo_warning, crash_warning=crash_warning) engine.game_data = game_data game_data.engine = engine game_data.set_up_game(ship_name, captain_name) game_data.info_description = game_data.describe_info() return engine
def render_other_ship_info(console: Console, gamedata:GameData, ship:Optional[Starship]=None): start_x = CONFIG_OBJECT.other_ship_display_x start_y = CONFIG_OBJECT.other_ship_display_y width = CONFIG_OBJECT.other_ship_display_end_x - CONFIG_OBJECT.other_ship_display_x height = CONFIG_OBJECT.other_ship_display_end_y - CONFIG_OBJECT.other_ship_display_y ship_planet_or_star = gamedata.selected_ship_planet_or_star if ship_planet_or_star: if isinstance(ship_planet_or_star, Starship): if not gamedata.ship_scan: gamedata.ship_scan = gamedata.selected_ship_planet_or_star.scan_for_print( gamedata.player.sensors.determin_precision ) print_ship_info( console=console, x=start_x, y=start_y, width=width, height=height, self=ship_planet_or_star, scan=gamedata.ship_scan, precision=gamedata.player.sensors.determin_precision ) elif isinstance(ship_planet_or_star, Planet): console.draw_frame( x=start_x, y=start_y, width=width, height=height, title="Planet" ) console.print( x=start_x+3, y=start_y+4, string=f"Planet at {ship_planet_or_star.local_coords.x}, {ship_planet_or_star.local_coords.y}" ) planet_status = ship_planet_or_star.planet_habbitation.description console.print_box( x=start_x+3, y=start_y+6, width=width-6, height=6, string=f"Planet status: {planet_status}\n\nPlanet development: {ship_planet_or_star.infastructure:.3}" ) elif isinstance(ship_planet_or_star, Star): console.draw_frame( x=start_x, y=start_y, width=width, height=height, title="Star" ) x, y = ship_planet_or_star.local_coords.x, ship_planet_or_star.local_coords.y console.print_rect( x=start_x+3, y=start_y+4, string=f"{ship_planet_or_star.name} star at {x}, {y}", height=4, width=width - (3 + 2) ) else: console.draw_frame( x=start_x, y=start_y, width=width, height=height, title="No Ship/Planet Selected" )
class Server: def __init__(self): self.server_port = 0 self.server_ip = NETWORK_ADDR self.server_socket = None self.selector = selectors.DefaultSelector() self.udp_broadcast_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.udp_broadcast_socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) self.broadcast_thread = None self.run_broadcast = True self.broadcast_iterations = 0 self.init_server_socket() self.offer = Offer(self.server_port) self.on_game = False self.init_groups_data() self.game_data = GameData() """ ========================= ==== Server network ===== ========================= """ """ Initialize the server socket and the selector """ def init_server_socket(self): self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.server_socket.setblocking(False) self.server_socket.bind((self.server_ip, self.server_port)) self.selector.register(self.server_socket, selectors.EVENT_READ, self.accept) #host_name = socket.gethostname() #self.server_ip = socket.gethostbyname(host_name) self.server_port = self.server_socket.getsockname()[1] print("Server started,listening on IP address {}".format( self.server_ip)) #init broadcast thread self.broadcast_thread = None #remove print("port", self.server_port) """ Start the udp broadcast """ def start_udp_broadcast(self): self.run_broadcast = True self.broadcast_iterations = 0 self.broadcast_thread = threading.Thread( target=self.udp_broadcast).start() """ UDP broadcast core, send the broadcast 10 times One broadcast every second """ def udp_broadcast(self): while (self.broadcast_iterations < 10): self.broadcast_iterations = self.broadcast_iterations + 1 #remove print("sending broadcast") self.udp_broadcast_socket.sendto( self.offer.get_bytes(), (BROADCAST_IP_ADDR, BROADCAST_PORT)) try: time.sleep(1) except SleepInterruptedException: continue self.on_game = True """ Add the socket to one of the play gorups evenly """ def add_socket_to_group(self, socket, team_name): self.connection_without_team_name.pop(socket, None) self.connection.append(socket) if (self.group_index == 0): self.group1[0][socket] = team_name self.groups_dict[socket] = self.group1 self.group_index = 1 else: self.group2[0][socket] = team_name self.groups_dict[socket] = self.group2 self.group_index = 0 """ Remove the client from the game. """ def remove_client_from_game(self, client_socket): client_socket.close() self.connection.remove(client_socket) if (((self.group_index) % 2) == 0): self.group2[0].pop(client_socket, None) else: self.group1[0].pop(client_socket, None) if (client_socket in self.groups_dict): self.groups_dict.pop(client_socket, None) self.selector.unregister(client_socket) """ Method to handle new connetion to the server. Insert the client socket to the selector to handle the data he need to send (the name of the team) """ def accept(self, socket, m): conn, addr = socket.accept() conn.setblocking(False) #self.add_socket_to_group(conn) self.connection_without_team_name[conn] = "" self.selector.register(conn, selectors.EVENT_READ, self.recv_user_name) """ Ignore all the data from the client. This method is for cleaning the socket read buffer before the game """ def ignore_user_data(self, client_socket, m): try: client_socket.fileno() data = client_socket.recv(256) if (len(data) == 0): self.remove_client_from_game(client_socket) except OSError: self.remove_client_from_game(client_socket) """ Method to handle the data from the client before the game starts The data need to be the team name. After the data was recived modify the selecotr data of the client read event to be the ignore_user_data method. Use the ignore_user_data until the game will start """ def recv_user_name(self, client_socket, m): try: client_socket.fileno() name_encoded = client_socket.recv(1024) if (len(name_encoded) > 0): name = decode(name_encoded) nl_char_index = name.find("\n") if (nl_char_index != -1): name = self.connection_without_team_name[ client_socket] + name[:nl_char_index] self.add_socket_to_group(client_socket, name) else: self.connection_without_team_name[ client_socket] = self.connection_without_team_name[ client_socket] + name self.selector.modify(client_socket, selectors.EVENT_READ, self.ignore_user_data) else: self.remove_client_from_game(client_socket) except OSError: self.remove_client_from_game(client_socket) """ The main method of the server. """ def run(self): self.start_udp_broadcast() self.server_socket.listen(10) while True: events = self.selector.select(0.1) for key, m in events: callback = key.data callback(key.fileobj, m) if (self.on_game): self.run_game_wrapper() self.server_socket.close() """ ========================= ======= Game core ======= ========================= """ """ Init the groups data. Use it before each game """ def init_groups_data(self): self.group_index = 0 self.groups_dict = {} self.group1 = [{}, 0] self.group2 = [{}, 0] self.connection = [] self.connection_without_team_name = {} """ Return all the group names from the group dict """ def get_group_name(self, group_dict): group_names = "" for key in group_dict: group_names = group_names + group_dict[key] + "\n" return group_names """ Return the start game message. The message follows the format """ def create_start_game_message(self): server_name = self.server_name_message() message = "Welcome to Keyboard Spamming Battle Royale.\n" start_sentence = "\nStart pressing keys on your keyboard as fast as you can!!\n" names_grop1 = "Group1:\n==\n" names_grop1 = names_grop1 + self.get_group_name(self.group1[0]) names_grop2 = "\nGroup2:\n==\n" names_grop2 = names_grop2 + self.get_group_name(self.group2[0]) return server_name + message + names_grop1 + names_grop2 + start_sentence """ Return the message that concludes the game The message follow the format. In addition there are some stat of the games to this point. """ def create_winners_message(self): group1_points = self.group1[1] group2_points = self.group2[1] points_message = "Group 1 typed in {0} characters. Group 2 typed in {1} characters.\n".format( group1_points, group2_points) group_names = "Congratulations to the winners:\n==\n" if (group1_points - group2_points == 0): winning_group_message = "Both groups win!\n\n" winners_name1 = self.get_group_name(self.group1[0]) winners_name2 = self.get_group_name(self.group2[0]) group_dict = self.group1[0] for key in group_dict: self.game_data.add_winner(group_dict[key]) group_dict = self.group2[0] for key in group_dict: self.game_data.add_winner(group_dict[key]) return points_message + winning_group_message + group_names + winners_name1 + winners_name2 winning_group_index = 1 winning_group = self.group1 if (group1_points - group2_points < 0): winning_group_index == 2 winning_group = self.group2 winning_group_message = "Group {0} wins!\n\n".format( winning_group_index) winners_name = self.get_group_name(winning_group[0]) group_dict = winning_group[0] for key in group_dict: self.game_data.add_winner(group_dict[key]) group_names = group_names + winners_name return points_message + winning_group_message + group_names def server_name_message(self): server_name = ''' _ __ __ __ ____ _ __ / | / /__ / /______ ____ ____/ /___ _ / __ \_____(_) /__ / |/ / _ \/ //_/ __ \/ __ \/ __ / __ `/ / /_/ / ___/ / //_/ / /| / __/ ,< / /_/ / /_/ / /_/ / /_/ / / ____(__ ) / ,< /_/ |_/\___/_/|_|\____/\____/\__,_/\__,_/ /_/ /____/_/_/|_| ''' return server_name """ Return the stat message. """ def create_stat_of_the_games_message(self): top_message = "========================\n\tGAME STATS:\n\n" close_stat_message = "\n========================\n" top_teams_message = "Top teams:\n" top_teams = self.game_data.get_top_three_winners() index = 1 for team in top_teams: team_message = " {0}. {1} with {2} points\n".format( index, team[0], team[1]) top_teams_message = top_teams_message + team_message index = index + 1 number_of_games = self.game_data.get_number_of_games() number_of_games_message = "Number of games played: {0}\n".format( number_of_games) most_used_char_tuple = self.game_data.get_most_used_char() most_use_char_message = "Most used char: '{0}' with {1} uses\n".format( most_used_char_tuple[0], most_used_char_tuple[1]) return top_message + top_teams_message + number_of_games_message + most_use_char_message + close_stat_message """ The run game method. This method wraps the run_game_method in order to clean the data after the game and initialize and organize the server socket and selector """ def run_game_wrapper(self): self.selector.unregister(self.server_socket) self.run_game() print("start sending out offer requests...") self.selector.register(self.server_socket, selectors.EVENT_READ, self.accept) self.on_game = False self.start_udp_broadcast() """ Start the game """ def run_game(self): print("starting the game") self.game_data.inc_number_of_games() start_game_message_encoded = encode_string( self.create_start_game_message()) for client in self.connection: try: client.send(start_game_message_encoded) except OSError: self.remove_client_from_game(client) self.game_core() if (len(self.connection) == 0): self.clean_game() return winning_group_message = self.create_winners_message() game_stat_message = self.create_stat_of_the_games_message() all_game_data_message = encode_string(winning_group_message + game_stat_message) for client in self.connection: try: client.send(all_game_data_message) except OSError: self.remove_client_from_game(client) self.clean_game() """ This method is the game core which is the code that recive the keys from the client and handling it. """ def game_core(self): game_running_since_second = time.time() game_running_for_seconds = 0 while (game_running_for_seconds < 10): events = self.selector.select(0.1) for key, m in events: client = key.fileobj ch = decode(client.recv(1)) #client close the game if (len(ch) == 0): try: self.connection.remove(client) except: pass self.selector.unregister(client) continue self.game_data.add_char(ch[0]) group_array = self.groups_dict[client] group_array[1] = group_array[1] + 1 game_running_for_seconds = time.time() - game_running_since_second """ Clean the game data. """ def clean_game(self): print("cleaning the game") for client in self.connection: self.selector.unregister(client) client.close() self.init_groups_data()
def get_games(self): database = Database() week_data = database.load_week_data(self.year, self.week_number) games = [] for game in week_data.games.values(): data = GameData() data.number = game.gamenum data.team1 = game.team1.team_name data.team2 = game.team2.team_name data.team1_score = self.__get_team1_score(game) data.team2_score = self.__get_team2_score(game) data.state = game.game_state data.quarter = self.__get_quarter(game) data.time_left = self.__get_time_left(game) data.date = game.kickoff games.append(data) return sorted(games, key=lambda game: game.number)
def button(msg, x, y, w, h, ic, ac, action=None): mouse = pygame.mouse.get_pos() click = pygame.mouse.get_pressed() if x + w > mouse[0] > x and y + h > mouse[1] > y: pygame.draw.rect(screen, ac, (x, y, w, h)) if click[0] == 1 and action != None: action() else: pygame.draw.rect(screen, ic, (x, y, w, h)) message_display(msg, black, (x + (w / 2)), (y + (h / 2)), 30) pygame.init() screen = pygame.display.set_mode(GameData().size) pygame.display.set_caption("Connect Four | Mayank Singh") message_display("CONNECT FOUR", yellow, 350, 150, 75) message_display("HAVE FUN!", (23, 196, 243), 350, 300, 75) running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False button("PLAY", 125, 450, 150, 60, white, green, startgame) button("QUIT", 425, 450, 150, 60, white, red, quitgame) pygame.display.update()
def start_main_loop(self): while True: keys = pygame.key.get_pressed() if isinstance(self.scene, Level): if keys[pygame.K_LEFT]: self.scene.battleship.go_left() if keys[pygame.K_RIGHT]: self.scene.battleship.go_right() if keys[pygame.K_DOWN]: self.scene.battleship.go_down() if keys[pygame.K_UP]: self.scene.battleship.go_up() # autofire # if keys[pygame.K_LCTRL]: # self.fire() for event in pygame.event.get(): if event.type == KEYUP: if event.key == K_LEFT: self.scene.battleship.get_straight(True) if event.key == K_RIGHT: self.scene.battleship.get_straight(False) if event.type == KEYDOWN: if isinstance(self.scene, Level): if event.key == K_LCTRL: self.scene.battleship.fire() if isinstance(self.scene, Intro): if event.key == K_1: self.game_data = GameData(self.screen) self.level_current = 0 self.scene = self.levels[self.level_current]( self.game_data) self.scene.start() if isinstance(self.scene, Credits): if event.key == K_SPACE: self.level_current = 0 self.scene = Intro() self.scene.start() if event.type == QUIT: pygame.quit() sys.exit(0) # check level status if isinstance(self.scene, Level): if self.scene.game_over: self.level_current = 0 self.scene = GameOver() self.scene.start() if self.scene.load_next_scene: self.level_current += 1 try: self.scene = self.levels[self.level_current]( self.game_data) self.scene.start() except IndexError: # show credits self.level_current = 0 self.scene = Credits() self.scene.start() if isinstance(self.scene, GameOver): if self.scene.load_next_scene: self.level_current = 0 self.scene = Intro() self.scene.start() if isinstance(self.scene, Intro): if self.scene.load_next_scene: self.level_current = 0 self.game_data = GameData(self.screen) self.scene = self.levels[self.level_current]( self.game_data) self.scene.start() # update level self.scene.update() # blit everything self.scene.draw(self.screen) # update score self.game_data.update() # clear up the dead if isinstance(self.scene, Level): self.scene.clear_the_dead() pygame.display.flip() self.clock.tick(FPS)
from connect import Connect from game_data import GameData from csv_maker import CSVMaker if __name__ == "__main__": connection = Connect() connection.connect() data = connection.query('SELECT * FROM "Games" ORDER BY id DESC LIMIT 5') # data = connection.query('SELECT * FROM "Games" WHERE id= \'22P7Erfe2Li\' LIMIT 1') csv_maker: CSVMaker = CSVMaker() for d in data: g_data = GameData(d) g_data.print_summary() csv_maker.generate_csv(g_data)
def get_game_states(replay_file): events = get_events(replay_file) game_data = GameData() game_data.record_events(events) return game_data.normalized_states
event for event in tracker_events_gen if event['_event'] in relevant_tracker_event_types ] game_events = [ event for event in game_events_gen if event['_event'] == "NNet.Game.SGameUserLeaveEvent" ] return tracker_events + game_events def get_game_states(replay_file): events = get_events(replay_file) game_data = GameData() game_data.record_events(events) return game_data.normalized_states if __name__ == '__main__': unit_type_names = set([]) replay_files = get_replay_files() for i in range(5): if i % 10 == 9: print("Processing replay {0} of {1}".format( i + 1, len(replay_files))) game_states = get_game_states(replay_files[i]) final_state = game_states[-1] print(GameData.state_to_string(final_state))
import pygame from pygame.locals import KEYDOWN from connect_game import ConnectGame from events import MouseClickEvent, MouseHoverEvent, bus from game_data import GameData from game_renderer import GameRenderer pygame.init() data = GameData() screen = pygame.display.set_mode(data.size) game = ConnectGame(data, GameRenderer(screen, data)) game.print_board() game.draw() pygame.display.update() pygame.time.wait(1000) # Processes mouse and keyboard events, dispatching events to the event bus. # The events are handled by the ConnectGame and GameRenderer classes. while not game.game_data.game_over: for event in pygame.event.get(): if event.type == pygame.QUIT: game.quit() if event.type == pygame.MOUSEMOTION: bus.emit("mouse:hover", game.renderer, MouseHoverEvent(event.pos[0]))
def get_game_data(): """ :return a GameDataType object (parsed proto) """ return GameData(get_static_data())
def start(): print("+++++++++++++++ start +++++++++++++++++++++++") #NOTE: None means Human player p1 = None # red p2 = None # yellow if args.player1 != HUMAN: # print ("p1 is NOT human") p1 = getAgent(args.player1) if args.player2 != HUMAN: # print ("p2 is NOT human") p2 = getAgent(args.player2) data = GameData() screen = pygame.display.set_mode(data.size) game = ConnectGame(data, GameRenderer(screen, data)) game.print_board() game.draw() pygame.display.update() pygame.time.wait(1000) #NOTE: data.turn of 0 == player 1 # data.turn of 1 == player 2 # Processes mouse and keyboard events, dispatching events to the event bus. # The events are handled by the ConnectGame and GameRenderer classes. p_is_human, p = getPlayer(p1, p2, data) #TODO - better way to clean screen? bus.emit("mouse:hover", game.renderer, MouseHoverEvent(-50)) while not game.game_data.game_over: pygame.time.wait(10) if p_is_human: for event in pygame.event.get(): if event.type == pygame.QUIT: game.quit() if event.type == pygame.MOUSEMOTION: bus.emit("mouse:hover", game.renderer, MouseHoverEvent(event.pos[0])) pygame.display.update() if event.type == pygame.MOUSEBUTTONDOWN: # print("HUMAN: Mouse:",PLAYER(data.turn),p_is_human,p) bus.emit("mouse:click", game, MouseClickEvent(event.pos[0])) p_is_human, p = getPlayer(p1, p2, data) # if event.type == KEYDOWN: # if event.key == pygame.K_z: # mods: int = pygame.key.get_mods() # if mods & pygame.KMOD_CTRL: # bus.emit("game:undo", game) else: #AI print("AI:", PLAYER(data.turn), p.get_name()) game.make_movement(p.get_move(data), p.get_name()) p_is_human, p = getPlayer(p1, p2, data) #keep pygame happy - otherwise freezes for event in pygame.event.get(): pass game.update() game.draw() print("--------------------- GAME OVER ----------------------------") pygame.display.update()
def start_main_loop(self): while True: keys = pygame.key.get_pressed() if isinstance(self.scene, Level): if keys[pygame.K_LEFT]: self.scene.battleship.go_left() if keys[pygame.K_RIGHT]: self.scene.battleship.go_right() if keys[pygame.K_DOWN]: self.scene.battleship.go_down() if keys[pygame.K_UP]: self.scene.battleship.go_up() # autofire # if keys[pygame.K_LCTRL]: # self.fire() for event in pygame.event.get(): if event.type == KEYUP: if event.key == K_LEFT: self.scene.battleship.get_straight(True) if event.key == K_RIGHT: self.scene.battleship.get_straight(False) if event.type == KEYDOWN: if isinstance(self.scene, Level): if event.key == K_LCTRL: self.scene.battleship.fire() if isinstance(self.scene, Intro): if event.key == K_1: self.game_data = GameData(self.screen) self.level_current = 0 self.scene = self.levels[self.level_current](self.game_data) self.scene.start() if isinstance(self.scene, Credits): if event.key == K_SPACE: self.level_current = 0 self.scene = Intro() self.scene.start() if event.type == QUIT: pygame.quit() sys.exit(0) # check level status if isinstance(self.scene, Level): if self.scene.game_over: self.level_current = 0 self.scene = GameOver() self.scene.start() if self.scene.load_next_scene: self.level_current += 1 try: self.scene = self.levels[self.level_current](self.game_data) self.scene.start() except IndexError: # show credits self.level_current = 0 self.scene = Credits() self.scene.start() if isinstance(self.scene, GameOver): if self.scene.load_next_scene: self.level_current = 0 self.scene = Intro() self.scene.start() if isinstance(self.scene, Intro): if self.scene.load_next_scene: self.level_current = 0 self.game_data = GameData(self.screen) self.scene = self.levels[self.level_current](self.game_data) self.scene.start() # update level self.scene.update() # blit everything self.scene.draw(self.screen) # update score self.game_data.update() # clear up the dead if isinstance(self.scene, Level): self.scene.clear_the_dead() pygame.display.flip() self.clock.tick(FPS)
def get_nparray(replay_file): events = get_events(replay_file) game_data = GameData() game_data.record_events(events) return game_data.convert_to_nparray()