def _find_lobby(self): """Find lobbies around the user.""" user = session.query(User).filter( User.id == self.request["greydId"]).first() lobbies = session.query(Lobby).join( Lobby.creator_user).filter(User.city == user.city).all() lobby_list = [] for lobby in lobbies: # If same city and lobby in 2 kilometer add list. circle = great_circle(lobby.center_location, user.location) if circle < 2: lobby_info = { "lobbyId": lobby.id, "lobbyName": lobby.name, "lobbyCreatorGreydId": lobby.creator_id, "lobbyCreatorFullName": lobby.creator_user.full_name, "lobbyCreatorFacebookId": lobby.creator_user.facebook_id, "gameMaxTime": lobby.max_time, "gameMaxLife": lobby.life_number, "lobbyGameDistance": lobby.game_distance, "lobbyCenterLocation": lobby.center_location } lobby_list.append(lobby_info) return { "success": True, "greydRule": self.request["greydRule"], "lobbies": lobby_list }
def _start_game(self): """Lobby creator start the game and first bait users will be notified. """ lobby = session.query(Lobby).filter( Lobby.id == self.request["lobbyId"]).first() # Add remaining life all lobby users. users = session.query(UserToLobby).filter( UserToLobby.lobby == lobby).all() for user in users: user.remaining_life = lobby.life_number session.commit() # Has user permission on the lobby? if self.request["greydId"] == lobby.creator_id: # noqa pylint: disable=no-else-return lobby.start_game() self.logger.info("Game Started LobbyId: %s", lobby.id) return { "success": True, "greydId": self.request["greydId"], "greydRule": self.request["greydRule"], "lobbyId": lobby.id, "lobbyStatus": lobby.status, "firstBaitLocation": lobby.bait_location } else: self.logger.warning( "Unauthorized start game request. GreydId: %s, LobbyId: %s", self.request["greydId"], lobby.id) return {"success": False, "errorType": "Unauthorized request"}
def _join_lobby(self): """User join the lobby proccess.""" lobby = session.query(Lobby).filter( Lobby.id == self.request["lobbyId"]).first() lobby_session = UserToLobby(lobby_id=self.request["lobbyId"], user_id=self.request["greydId"], entry_time=self.time_now, remaining_life=lobby.life_number) session.add(lobby_session) session.commit() self.logger.info("GreydId: %s joined the lobby. LobbyId: %s", self.request["greydId"], lobby.id) lobby_users = session.query(UserToLobby).join(UserToLobby.user).filter( UserToLobby.lobby_id == lobby_session.lobby_id).all() user_list = [] for lobby_user in lobby_users: user_list.append({ "userGreydId": lobby_user.user.id, "userFacebookId": lobby_user.user.facebook_id }) return { "success": True, "greydRule": self.request["greydRule"], "greydId": self.request["greydId"], "lobbyId": lobby.id, "users": user_list }
def _game_result(self): """Game Result. Find winner user.""" self.lobby.end_game() winner_session = session.query(UserToLobby).order_by( UserToLobby.collected_bait.desc()).first() winner_session.is_game_won = True session.commit()
def played_games_info(greyd_id): """Information about past games of users. Total game number, game time and how many won game. """ sessions = session.query(UserToLobby).filter( UserToLobby.user_id == greyd_id).all() game_number = game_time = game_won = 0 for game in sessions: game_number += 1 if game.is_game_won: game_won += 1 time_format = '%m/%d/%Y %H:%M' entry_time = datetime.strptime(game.entry_time, time_format) exit_time = datetime.strptime(game.exit_time, time_format) if entry_time < exit_time: time_diff = exit_time - entry_time time_diff = int(time_diff.total_seconds()) game_time += time_diff return {"totalGame": game_number, "totalGameTime": game_time, "wonGame": game_won}
def _points_inc_dec(self): """Add 1 point for bait taken user and other user lost 1 life.""" user = session.query(User).filter( User.id == self.request["greydId"]).first() user.add_point() users_session = session.query(UserToLobby).filter( UserToLobby.lobby_id == self.lobby.id).filter( UserToLobby.remaining_life > 0).all() for user_session in users_session: # User is won the bait then increase the collected bait # else then user lose the life. if user_session.id == self.session_id: user_session.collected_bait = user_session.collected_bait + 1 else: user_session.remaining_life = user_session.remaining_life - 1 session.commit()
def _user_info_same_lobby(self): """Get other users info and chat info.""" lobby_users = session.query(UserToLobby).join(UserToLobby.user).filter( UserToLobby.lobby_id == self.request["lobbyId"]).all() user_list = [] for lobby_user in lobby_users: # Find how many taken bait in this lobby. user_taken_bait = session.query(UserLocation).filter( UserLocation.session_id == lobby_user.id).filter( UserLocation.is_bait_taken).count() user_info = { "userGreydId": lobby_user.user.id, "userFacebookId": lobby_user.user.facebook_id, "userFullName": lobby_user.user.full_name, "userScore": lobby_user.user.total_score, "userLocation": lobby_user.user.location, "userTotalBait": user_taken_bait } # Add chat data in response chats = session.query(Chat).filter( Chat.session_id == lobby_user.id).filter( Chat.id > self.request["lastSeenChatId"]).all() user_chat = [] for chat in chats: chat_info = { "chatId": chat.id, "chatTime": chat.time, "chatContent": chat.content } user_chat.append(chat_info) user_list.append(user_info) return user_list
def played_distance(greyd_id): """Calculate user how many meter walk on game history.""" from geopy.distance import distance locations = session.query(UserLocation).join(UserToLobby).filter( UserLocation.session_id == UserToLobby.id).filter( UserToLobby.user_id == greyd_id).order_by( UserLocation.session_id.asc()).all() user_distance = 0 for location1, location2 in zip(locations, locations[1:]): if location1[0] == location2[0]: user_distance += distance(location1[1], location2[1]).m return user_distance
def _leave_lobby(self): """User quit the lobby""" lobby = session.query(Lobby).filter( Lobby.id == self.request["lobbyId"]).first() # Is lobby creator? if self.request["greydId"] == lobby.creator_id: lobby.end_game() # All session is terminating. users_session = session.query(UserToLobby).filter( UserToLobby.lobby_id == lobby.id).all() users_session.exit_time = self.time_now self.logger.info("The lobby owner ended the lobby. LobbyId: %s", lobby.id) winner_session = session.query(UserToLobby).order_by( UserToLobby.collected_bait.desc()).first() winner_session.is_game_won = True session.commit() else: lobby_session = session.query(UserToLobby).filter( UserToLobby.lobby_id == self.request["lobbyId"]).filter( UserToLobby.user_id == self.request["greydId"]).first() lobby_session.exit_time = self.time_now lobby_session.is_game_won = False self.logger.info("User left the lobby. GreydId: %s", self.request["greydId"]) session.commit() return { "success": True, "greydRule": self.request["greydRule"], "greydId": self.request["greydId"], "lobbyId": lobby.id }
def _is_game_end(self): """Control of game. Control authorization only lobby creator.""" if self.lobby.creator_id != self.request["greydId"]: return # Check time ending start_time = datetime.strptime(self.lobby.start_time, '%m/%d/%Y %H:%M') expecting_end_time = start_time + \ timedelta(minutes=self.lobby.max_time) if expecting_end_time <= datetime.now(): self._game_result() # Check life ending # How many user have more than 0 life user_still_playing = session.query(UserToLobby).filter( UserToLobby.lobby_id == self.lobby.id).filter( UserToLobby.remaining_life > 0).count() if user_still_playing < 0: self._game_result()
def _facebook_login(self): user = session.query(User).filter( User.facebook_id == self.request["facebookId"]).first() if not user: # If user does not exist. user = User(facebook_id=self.request["facebookId"], full_name=self.request["fullName"], e_mail=self.request["eMail"]) session.add(user) session.commit() self.logger.info("New Facebook user GreydId: %s, FacebookId: %s", user.id, user.facebook_id) # Update location information this login. user.location = self.request["location"] user.city_update() session.commit() self.logger.info("User logged in GreydId: %s", user.id) return {"success": True, "greydRule": self.request["greydRule"], "greydId": user.id, "userStatus": user.status}
def _get_lobby(self): """Return lobby.""" return session.query(Lobby).filter( Lobby.id == self.request["lobbyId"]).first()
def _get_facebook_friends_players(self): friends_facebook_ids = self.request["friendsFacebookId"] friends = session.query(User).filter(User.id.in_( friends_facebook_ids)).all() return self._user_info(friends)
def _get_top_city_players(self, number_of_player=10): users = session.query(User).filter( User.city == self.user.city).order_by( User.total_score.desc()).limit(number_of_player).all() return self._user_info(users)
def _get_top_players(self, number_of_player=10): """Get information of the top n players (default=10).""" users = session.query(User).order_by(User.total_score.desc()).limit( number_of_player).all() return self._user_info(users)
def __init__(self, request): self.request = request self.user = session.query(User).filter( User.id == self.request["greydId"]).first()
def _get_session_id(self): """Return session id.""" return session.query(UserToLobby.id).filter( UserToLobby.lobby_id == self.request["lobbyId"]).filter( UserToLobby.user_id == self.request["greydId"]).first()[0]