Esempio n. 1
0
 def __init__(self, connection, tournament_id):
     print("Hello TournamentController")
     self.tournament_model = TournamentModel(connection)
     self.song_tournament_model = SongTournamentModel(connection)
     self.game_model = GameModel(connection)
     self.tournament_id = tournament_id
     self.elo_calc = EloCalculator()
Esempio n. 2
0
    def __init__(self, app):
        super().__init__(parent_controller=app,
                         logger=getLogger('root.app.game.controller'))
        self.view = GameView(controller=self)
        self.model = GameModel(controller=self, view=self.view)
        self.fade_in_animation = GameFadeInAnimation(self.view)
        self.fade_out_animation = GameFadeOutAnimation(self.view)
        self.bonus_code_manager = BonusCodeManagerController(self)
        self.map_switcher = MapSwitcherController(self)
        self.maps = [PassengerMapController(self), FreightMapController(self)]
        self.fade_in_animation.bonus_code_manager_fade_in_animation = self.bonus_code_manager.fade_in_animation
        self.fade_out_animation.bonus_code_manager_fade_out_animation = self.bonus_code_manager.fade_out_animation
        self.fade_in_animation.map_switcher_fade_in_animation = self.map_switcher.fade_in_animation
        self.fade_out_animation.map_switcher_fade_out_animation = self.map_switcher.fade_out_animation
        for m in self.maps:
            self.fade_in_animation.map_fade_in_animations.append(
                m.fade_in_animation)
            self.fade_out_animation.map_fade_out_animations.append(
                m.fade_out_animation)

        self.child_controllers = [
            self.bonus_code_manager, self.map_switcher, *self.maps
        ]
        self.map_transition_animations = {
            PASSENGER_MAP: {
                FREIGHT_MAP:
                TransitionAnimation(
                    fade_out_animation=self.maps[PASSENGER_MAP].
                    fade_out_animation,
                    fade_in_animation=self.maps[FREIGHT_MAP].fade_in_animation)
            },
            FREIGHT_MAP: {
                PASSENGER_MAP:
                TransitionAnimation(fade_out_animation=self.maps[FREIGHT_MAP].
                                    fade_out_animation,
                                    fade_in_animation=self.maps[PASSENGER_MAP].
                                    fade_in_animation)
            }
        }
Esempio n. 3
0
class GameUpdate(object):

    def __init__(self, connection, game_id):
        self.song_tournament_model = SongTournamentModel(connection)
        self.elo_calc = EloCalculator()
        self.game_model = GameModel(connection)
        self.req_data = json.loads(request.data)
        self.game_id = game_id

    def init(self):

        song_left_new_rating = self.song_tournament_model.get_current_rating_by_id(self.req_data['tournament-id'],self.req_data['song-left-id'])
        song_right_new_rating = self.song_tournament_model.get_current_rating_by_id(self.req_data['tournament-id'],self.req_data['song-right-id'])

        print(self.req_data)

        result = self.elo_calc.get_result(
            song_left_new_rating['rating'],
            self.req_data['song-left-score'],
            True, True,
            self.req_data['song-right-score'],
            song_right_new_rating['rating']
        )

        self.game_model.update_game({
            'id': self.game_id,
            'tournament_id' : self.req_data['tournament-id'],
            'song_left_id' : self.req_data['song-left-id'],
            'song_left_before_rating' : song_left_new_rating['rating'],
            'song_left_after_rating' : result[0][0],
            'song_left_score' : self.req_data['song-left-score'],
            'song_right_score' : self.req_data['song-right-score'],
            'song_right_after_rating' : result[1][0],
            'song_right_before_rating' : song_right_new_rating['rating'],
            'song_right_id' : self.req_data['song-right-id']
        })
        return json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
Esempio n. 4
0
class GameController(GameBaseController):
    def __init__(self, app):
        super().__init__(parent_controller=app,
                         logger=getLogger('root.app.game.controller'))
        self.view = GameView(controller=self)
        self.model = GameModel(controller=self, view=self.view)
        self.fade_in_animation = GameFadeInAnimation(self.view)
        self.fade_out_animation = GameFadeOutAnimation(self.view)
        self.bonus_code_manager = BonusCodeManagerController(self)
        self.map_switcher = MapSwitcherController(self)
        self.maps = [PassengerMapController(self), FreightMapController(self)]
        self.fade_in_animation.bonus_code_manager_fade_in_animation = self.bonus_code_manager.fade_in_animation
        self.fade_out_animation.bonus_code_manager_fade_out_animation = self.bonus_code_manager.fade_out_animation
        self.fade_in_animation.map_switcher_fade_in_animation = self.map_switcher.fade_in_animation
        self.fade_out_animation.map_switcher_fade_out_animation = self.map_switcher.fade_out_animation
        for m in self.maps:
            self.fade_in_animation.map_fade_in_animations.append(
                m.fade_in_animation)
            self.fade_out_animation.map_fade_out_animations.append(
                m.fade_out_animation)

        self.child_controllers = [
            self.bonus_code_manager, self.map_switcher, *self.maps
        ]
        self.map_transition_animations = {
            PASSENGER_MAP: {
                FREIGHT_MAP:
                TransitionAnimation(
                    fade_out_animation=self.maps[PASSENGER_MAP].
                    fade_out_animation,
                    fade_in_animation=self.maps[FREIGHT_MAP].fade_in_animation)
            },
            FREIGHT_MAP: {
                PASSENGER_MAP:
                TransitionAnimation(fade_out_animation=self.maps[FREIGHT_MAP].
                                    fade_out_animation,
                                    fade_in_animation=self.maps[PASSENGER_MAP].
                                    fade_in_animation)
            }
        }

    @game_is_not_paused
    def on_update_time(self, dt):
        super().on_update_time(dt)
        if self.model.game_time % (SECONDS_IN_ONE_HOUR * 2) == 0:
            self.parent_controller.on_save_state()

    def on_resume_game(self):
        self.model.on_resume_game()

    def on_update_money_target(self, money_target):
        self.model.on_update_money_target(money_target)

    def on_add_exp(self, exp):
        self.model.on_add_exp(exp)

    def on_deactivate_money_target_for_inactive_maps(self, active_map_id):
        for m in [m for m in self.maps if m.map_id != active_map_id]:
            m.on_deactivate_money_target()

    def on_add_exp_bonus(self, exp_bonus):
        self.model.on_add_exp_bonus(exp_bonus)

    def on_activate_new_bonus_code(self, sha512_hash):
        self.bonus_code_manager.on_activate_new_bonus_code(sha512_hash)
        if (bonus_code_type :=
                BONUS_CODE_MATRIX[sha512_hash][CODE_TYPE]) == EXP_BONUS_CODE:
            self.on_activate_exp_bonus_code(
                BONUS_CODE_MATRIX[sha512_hash][BONUS_VALUE])
        elif bonus_code_type == MONEY_BONUS_CODE:
            self.on_activate_money_bonus_code(
                BONUS_CODE_MATRIX[sha512_hash][BONUS_VALUE])
Esempio n. 5
0
    def run(self):
        # initializes the model
        self.model = GameModel()

        # initialize the view with the model
        self.main_view = ViewMainWindow()
Esempio n. 6
0
 def __init__(self, connection, game_id):
     self.song_tournament_model = SongTournamentModel(connection)
     self.elo_calc = EloCalculator()
     self.game_model = GameModel(connection)
     self.req_data = json.loads(request.data)
     self.game_id = game_id
Esempio n. 7
0
def server():
    hostname = socket.gethostname()
    ip = socket.gethostbyname(hostname)
    # print("Enter port: ", end="")
    # port = sys.stdin.readline().split("\n")[0]
    # port = input("Enter port: ")
    port = 7777
    # print(port)
    # if not port.isdigit():
    #     port = 0
    # else:
    #     port = int(port)
    # print(int(ip))
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    """ tries to create socket at host ip address and port"""
    try:
        # s.bind((host_ip, port))
        s.bind((ip, port))
    except socket.error as err:
        print(err)
        return

    port = s.getsockname()[1]
    print(f'{ip}:{port}')
    """ sets the socket to start listening for incoming connections """
    s.listen(2)

    def client_connection_thread(client_connection, player_index, game_id,
                                 has_ended_ref):
        ready_sent = False
        highest = 0
        client_connection.send(str(player_index).encode()
                               )  # sends to client if they are player 1 or 2
        while True:
            try:
                player_input = json.loads(client_connection.recv(11))
                if not player_input:
                    print("NOT PLAYER")
                    games[game_id][2].acquire()
                    has_ended_ref[0] = True
                    print("Game has ended")
                    client_connection.sendall("none".encode())
                    games[game_id][2].release()
                    break
                else:
                    player_input = Dir[player_input]

                if game_id in games:
                    game = games[game_id]

                    # if game[0].ready and not ready_sent:
                    #     print("sending ready")
                    #     ready_sent = True
                    #     client_connection.sendall("ready".encode())

                    game[2].acquire()
                    game[1][player_index] = player_input
                    output_vehicles = []
                    for vehicle in game[0].vehicles:
                        # output_vehicles.append(vehicle.car_type)
                        for i in gv.CAR_TYPES:
                            if gv.CAR_TYPES[i] == vehicle.car_type:
                                output_vehicles.append(i)
                                break
                        output_vehicles.append(vehicle.x)
                        output_vehicles.append(vehicle.y)
                        output_vehicles.append(vehicle.health)
                        # output_vehicles.append(gv.WINDOW_W)
                        # output_vehicles.append(gv.WINDOW_L+gv.PLAYER_LENGTH)
                        # output_vehicles.append(1000)
                    game[2].release()
                    # print(output_vehicles)
                    # game_model_dict = get_json(game[0])
                    # game_model_str = json.dumps(game_model_dict)
                    # game_model_str = json.dumps(game_model_dict, indent=4)
                    if has_ended_ref[0]:
                        print("Game has ended")
                        client_connection.sendall("none".encode())
                        break
                    x = client_connection.send(
                        json.dumps(output_vehicles).encode())
                    # highest = max(highest, x)
                    # print(highest)
                else:
                    print("No game found")
                    client_connection.sendall("none".encode())
                    break
            except Exception as err:
                print("ERROR in client thread:", err)
                break
        has_ended_ref[0] = True
        print("Connection Lost")
        try:
            del games[game_id]
            print("closing game:", game_id)
        except Exception as err:
            print("game closed")
        client_connection.close()

    player_id = 0
    games = {}
    while True:
        client_connection, client_ip = s.accept()
        print("Connected to:", client_ip)
        game_id = player_id // 2
        player_index = player_id % 2
        if player_id % 2 == 0:
            has_ended_ref = [False]
            game_model = GameModel(ready=False, num_players=2)
            games[game_id] = (game_model, [Dir.NONE,
                                           Dir.NONE], Lock(), has_ended_ref)
            print(f"Creating game: {game_id}, waiting for player 2")
            start_new_thread(game_thread, (games[game_id], ))
        else:
            if game_id in games:
                print("Game Start!")
                games[game_id][0].ready = True
            else:
                player_id += 1
                game_id = player_id // 2
                player_index = player_id % 2
                games[game_id] = (GameModel(ready=False, num_players=2),
                                  [Dir.NONE, Dir.NONE], Lock(), [False])
                print(f"Creating game: {game_id}, waiting for player 2")
                start_new_thread(game_thread, (games[game_id], ))
        start_new_thread(
            client_connection_thread,
            (client_connection, player_index, game_id, games[game_id][3]))
        player_id += 1
        if player_id >= 999999999:
            print("After 999,999,999 iterations, the server stops")
            break
Esempio n. 8
0
class TournamentController(object):
    def __init__(self, connection, tournament_id):
        print("Hello TournamentController")
        self.tournament_model = TournamentModel(connection)
        self.song_tournament_model = SongTournamentModel(connection)
        self.game_model = GameModel(connection)
        self.tournament_id = tournament_id
        self.elo_calc = EloCalculator()

    def init(self):
        song_tournament = self.song_tournament_model.get_all_songs_by_tournament(
            self.tournament_id)
        games_played_tournament = self.game_model.get_games_by_tournament_id(
            self.tournament_id, True)
        games_future_tournament = self.game_model.get_games_by_tournament_id(
            self.tournament_id, False)

        projected_results = {'title': {'left': '', 'right': ''}, 'results': []}
        projected_scores = [(10, 0), (7, 3), (5, 5), (3, 7), (0, 10)]
        if (len(games_future_tournament) > 0):
            projected_results['title']['left'] = games_future_tournament[0][
                's1title']
            projected_results['title']['right'] = games_future_tournament[0][
                's2title']
            left_rating = games_future_tournament[0]['song_left_before_rating']
            right_rating = games_future_tournament[0][
                'song_right_before_rating']

            for ps_val in projected_scores:
                result = self.elo_calc.get_result(left_rating, ps_val[0], True,
                                                  True, ps_val[1],
                                                  right_rating)
                projected_results['results'].append({
                    'l_rating': result[0][0],
                    'l_score': ps_val[0],
                    'r_score': ps_val[1],
                    'r_rating': result[1][0]
                })

        song_tournament_rating = {}
        for st_val in song_tournament:
            games_per_song = self.game_model.get_games_by_song_id(
                self.tournament_id, st_val['song_id'])
            song_ratings = []

            if len(games_per_song) > 0:
                if st_val['song_id'] == games_per_song[0]['song_left_id']:
                    song_ratings.append(
                        games_per_song[0]['song_left_before_rating'])
                elif st_val['song_id'] == games_per_song[0]['song_right_id']:
                    song_ratings.append(
                        games_per_song[0]['song_right_before_rating'])

                for gs_val in games_per_song:
                    if st_val['song_id'] == gs_val['song_left_id']:
                        song_ratings.append(gs_val['song_left_after_rating'])
                    elif st_val['song_id'] == gs_val['song_right_id']:
                        song_ratings.append(gs_val['song_right_after_rating'])

            song_tournament_rating[st_val['song_id']] = {
                'song_ratings': song_ratings,
                'song_title': st_val['title']
            }

        tournament = self.tournament_model.get_one(self.tournament_id)

        resp = make_response(
            render_template(
                'tournament.html',
                tournament=tournament,
                song_tournaments=song_tournament,
                song_tournament_rating=song_tournament_rating,
                games_played_tournament=games_played_tournament,
                games_future_tournament=games_future_tournament,
                games_future_tournament_count=len(games_future_tournament),
                projected_results=projected_results))
        resp.set_cookie('usernametwo', 'theusername')

        return resp