Exemple #1
0
def join_existing_game(game: Game, player: Union[User, int]) -> Game:
    print(f"Player {player} of type {type(player)} is joining game {game}")

    if isinstance(player, int):
        print(f"Player {player} is an AI player")
        player_config = dict(
            human_player=None,
            ai_player=player,
        )
    else:
        print(f"Player {player} is a human player")
        if game.has_human_player(player):
            return game

        game.human_players.add(player)
        player_config = dict(
            human_player=player,
            ai_player=None,
        )
        if game.is_ready():
            Round(
                game=game,
                round_number=1,
            )

    rack = Rack(
        game=game,
        tiles=game.tile_bag.fill_rack(),
        **player_config,
    )
    commit()
    print(f"Created rack {rack} for human player {rack.human_player} and ai player {rack.ai_player}")
    num_racks = len(Rack.select()[:])
    print(f"Total number of racks: {num_racks}")
    return game
Exemple #2
0
class TestGame(TestCase):
    def setUp(self):
        self.game = Game()

    def test_create_game(self):
        self.assertTrue(self.game)

    def test_create_open_game(self):
        self.assertEqual(self.game.close, False)

    def test_finish_game(self):
        self.game.codebreaker.guess_code = 'B,P,W,R'
        self.game.codemaker.code = 'B,P,W,R'
        self.assertEqual(self.game._is_finished_game(), True)

    def test_get_black_pegs(self):
        self.game.codebreaker.guess_code = 'B,P,W,R'
        self.game.codemaker.code = 'B,Y,W,R'

        self.assertEqual(self.game.get_black_pegs(), 3)

    def test_get_white_pegs(self):
        self.game.codebreaker.guess_code = 'B,P,W,R'
        self.game.codemaker.code = 'P,B,W,R'

        self.assertEqual(self.game.get_white_pegs(), 2)

    def test_is_finished_game(self):
        self.game.codebreaker.guess_code = 'B,P,W,R'
        self.game.codemaker.code = 'B,P,W,R'

        self.assertTrue(self.game._is_finished_game())
def game(gameId):
    """
    Method associated the with the '/game=<gameId>' route where the
    gameId is in the URL.  
    
    Validates that the gameId actually exists.

    Checks to see if the game has been finished.
    
    Gets the state of the board and updates the visual representation
    accordingly.
    
    Displays a bit of extra information like turn, status, and gameId.
    """
    if session.get("username", None) == None:
        flash("Need to login")
        return redirect("/index")
    
    item = controller.getGame(gameId)
    if item == None: 
        flash("That game does not exist.")
        return redirect("/index")


    boardState = controller.getBoardState(item)
    result = controller.checkForGameResult(boardState, item, session["username"])

    if result != None:
        if controller.changeGameToFinishedState(item, result, session["username"]) == False:
            flash("Some error occured while trying to finish game.")

    game = Game(item)
    status   = game.status
    turn     = game.turn 

    if game.getResult(session["username"]) == None:
        if (turn == game.o):
            turn += " (O)"
        else:
            turn += " (X)"

    gameData = {'gameId': gameId, 'status': game.status, 'turn': game.turn, 'board': boardState};
    gameJson = json.dumps(gameData)
    return render_template("play.html",
                            gameId=gameId,
                            gameJson=gameJson,
                            user=session["username"],
                            status=status,
                            turn=turn,
                            opponent=game.getOpposingPlayer(session["username"]),
                            result=result,
                            TopLeft=boardState[0],
                            TopMiddle=boardState[1],
                            TopRight=boardState[2],
                            MiddleLeft=boardState[3],
                            MiddleMiddle=boardState[4],
                            MiddleRight=boardState[5],
                            BottomLeft=boardState[6],
                            BottomMiddle=boardState[7],
                            BottomRight=boardState[8])
Exemple #4
0
 def scrape(self, current_week):
     r = requests.get(self.url)
     _scores_data = r.json()
     for _game_id in _scores_data:
         _game = _scores_data[_game_id]
         _home = _game['home']
         _away = _game['away']
         home_score = _game['home']['score']['T']
         away_score = _game['away']['score']['T']
         home = NFL_DOT_COM_TEAM_MAPPINGS[_home['abbr']]
         away = NFL_DOT_COM_TEAM_MAPPINGS[_away['abbr']]
         result_set = session.query(Game.id).filter_by(week=current_week,
                                                       home=home).first()
         if result_set is not None:
             game = Game(id=result_set[0],
                         home_score=home_score,
                         away_score=away_score)
         else:
             game = Game(home=home,
                         week=current_week,
                         away=away,
                         away_score=away_score,
                         home_score=home_score)
         session.merge(game)
         session.commit()
Exemple #5
0
 def initialize_game(self, *, start_game):
     self.game = Game(table=self.table_green,
                      croupier=self.croupier,
                      money_min_to_connect=5,
                      game_players=self.table_green.person_at_the_table)
     if start_game:
         self.game.start_game()
def test_user_transformer_turns_user_data_into_user_obj(
        user_data, gun_stats_obj):
    games = [Game(appid=10, playtime=4600), Game(appid=20, playtime=2000)]
    stats = Csgo_stats(hours=1000,
                       total_kills=1000,
                       total_deaths=100,
                       defused_bombs=1000,
                       planted_bombs=1000,
                       money_earned=1000,
                       mvps=1000,
                       total_wins=1000,
                       knife_kills=1000,
                       shots_fired=1000,
                       shots_hit=1000,
                       rescued_hostages=507,
                       headshots=117038,
                       weapons_donated=8067,
                       dominations=3711,
                       revenges=317,
                       broken_windows=98,
                       gun_stats=gun_stats_obj)

    user = User_transformer().transform_user(user_data, games, stats)

    assert isinstance(user, User)
Exemple #7
0
 def test_change_playground_accepts_valid_time(self):
     """
     playtime ('2000', '2200') is valid in both playgrounds
     """
     game = Game(playground=self.playground_a, playtime=('2000', '2200'), players=self.players)
     game.change_playground(self.playground_b)
     self.assertEqual(game.get_playground(), self.playground_b)
Exemple #8
0
def generate_fixture_list(league):
    fixtures = []
    sql = "SELECT possible_games.team_1, possible_games.team_2, playlists.round_no FROM possible_games INNER JOIN fixtures ON fixtures.possible_game_id = possible_games.id INNER JOIN playlists ON fixtures.playlist_id = playlists.id INNER JOIN league_types ON league_types.id = playlists.league_type_id INNER JOIN leagues ON league_types.id = leagues.league_type_id WHERE leagues.id = %s"
    values = [league.id]
    results = run_sql(sql, values)

    game_no = 1
    for result in results:
        game = Game(result['team_1'], result['team_2'], league,
                    result['round_no'], game_no)
        fixtures.append(game)
        game_no += 1

    teams = []
    sql = "SELECT teams.* FROM teams INNER JOIN leagues ON leagues.id = teams.league_id WHERE leagues.id = %s"
    values = [league.id]
    results = run_sql(sql, values)
    for result in results:
        team = Team(league, result['name'], result['games_played'],
                    result['wins'], result['draws'], result['losses'],
                    result['goals_for'], result['goals_against'],
                    result['goal_difference'], result['points'], result['id'])
        teams.append(team)

    games = []
    for fixture in fixtures:
        team_1 = fixture.team_1
        team_2 = fixture.team_2
        game = Game(teams[team_1 - 1], teams[team_2 - 1], league,
                    fixture.round_no, fixture.game_no)
        games.append(game)

    return games
Exemple #9
0
 def test_change_playime_accepts_valid_time(self):
     """
     playtime ('1600', '1800') is fine
     """
     game = Game(playground=self.playground_a, playtime=('2000', '2200'), players=self.players)
     game.change_playtime(new_playtime=('1600', '1800'))
     self.assertEqual(game.get_playtime(), ('1600', '1800'))
Exemple #10
0
    def scrape(self, current_week):
        r = requests.get(self.url)
        response_data = json.loads(r.text)
        # filter out first half lines and other non-full-game lines
        games_data = [
            g for g in response_data['Leagues'][0]['Events']
            if g['PeriodNumber'] == 0
        ]
        for i, game_data in enumerate(games_data):
            away_team_data = game_data['Participants'][0]
            home_team_data = game_data['Participants'][1]
            spread = home_team_data['Handicap']['Min']
            away_team_name = PINNACLE_TEAM_MAPPINGS[away_team_data['Name']]
            home_team_name = PINNACLE_TEAM_MAPPINGS[home_team_data['Name']]

            result_set = session.query(Game.id).filter_by(
                week=current_week, home=home_team_name).first()
            if result_set is not None:
                game = Game(id=result_set[0], spread=spread)
            else:
                game = Game(home=home_team_name,
                            away=away_team_name,
                            week=current_week,
                            spread=spread)
            session.merge(game)
            session.commit()
Exemple #11
0
    def add_game(self, game: Game):
        with sqlite3.connect(self._db_path) as connection:
            cursor = connection.cursor()

            game_query = self.build_insert_query(
                table=GamesTable.TABLE_NAME,
                columns=(GamesTable.Columns.NAME,
                         GamesTable.Columns.START_DATE,
                         GamesTable.Columns.END_DATE))
            cursor.execute(game_query, _unpack_game(game))
            game.update_with_generated_id(cursor.lastrowid)

            for user in game.users:
                user_query = self.build_insert_query(
                    table=MembershipsTable.TABLE_NAME,
                    columns=(MembershipsTable.Columns.GAME_ID,
                             MembershipsTable.Columns.USERNAME))
                cursor.execute(user_query, (game.game_id, user.user_id))

            connection.commit()

            for portfolio in game.portfolios:
                portfolio_query = self.build_insert_query(
                    table=PortfoliosTable.TABLE_NAME,
                    columns=(PortfoliosTable.Columns.GAME_ID,
                             PortfoliosTable.Columns.PORTFOLIO_ID))
                cursor.execute(portfolio_query,
                               (game.game_id, portfolio.portfolio_id))
Exemple #12
0
    def new_game(self, request, user):
        """Creates new game"""
        if not user:
            raise endpoints.NotFoundException(
                    'A User with that name does not exist!')
        
        if (request.how_hard not in [1,2,3]):
            raise endpoints.NotFoundException \
            ('Invalid value. Pick a level 1, 2, or 3')

        ingamecheck=Game.query(Game.user==user.key).filter(
            Game.game_over == False).get()
        
        if not ingamecheck:
            taskqueue.add(
                params={
                'email': user.email,
                'name': user.name},
            url='/tasks/send_newgame_email', 
            method="POST")

            invenlist=self._inventlist(request)
            game=Game.new_game(user.key, request.how_hard)
            return game.to_form \
            ('Prepare to test your survival skills!')
        
        if ingamecheck.game_over == False:
            raise endpoints.ConflictException(
                'Only one active game per user is allowed'
                )
def start_simulation():
    '''
    Makes two *Computer* objects and starts the simulation mode.

    Returns
    -------
    None
    '''

    for level in Computer.allowed_levels:
        Ui.print_message("Option: {} ".format(level))
    proper_level = False
    while not proper_level:
        levels = Ui.get_inputs(["Level", "Level"], "Choose computer\'s level")
        comp1_level = levels[0]
        comp2_level = levels[1]
        if level in Computer.allowed_levels:
            proper_level = True

    computer1 = Computer(comp1_level)
    computer2 = Computer(comp2_level)
    computer2.name = "Computer2"

    gameplay = Game(computer1, computer2)
    gameplay.start_game()
Exemple #14
0
def game(gameId):
    """
    Method associated the with the '/game=<gameId>' route where the
    gameId is in the URL.

    Validates that the gameId actually exists.

    Checks to see if the game has been finished.

    Gets the state of the board and updates the visual representation
    accordingly.

    Displays a bit of extra information like turn, status, and gameId.
    """
    if session.get("username", None) == None:
        flash("Need to login")
        return redirect("/index")

    item = controller.getGame(gameId)
    if item == None:
        flash("That game does not exist.")
        return redirect("/index")


    boardState = controller.getBoardState(item)
    result = controller.checkForGameResult(boardState, item, session["username"])

    if result != None:
        if controller.changeGameToFinishedState(item, result, session["username"]) == False:
            flash("Some error occured while trying to finish game.")

    game = Game(item)
    status   = game.status
    turn     = game.turn

    if game.getResult(session["username"]) == None:
        if (turn == game.o):
            turn += " (O)"
        else:
            turn += " (X)"

    gameData = {'gameId': gameId, 'status': game.status, 'turn': game.turn, 'board': boardState};
    gameJson = json.dumps(gameData)
    return render_template("play.html",
                            gameId=gameId,
                            gameJson=gameJson,
                            user=session["username"],
                            status=status,
                            turn=turn,
                            opponent=game.getOpposingPlayer(session["username"]),
                            result=result,
                            TopLeft=boardState[0],
                            TopMiddle=boardState[1],
                            TopRight=boardState[2],
                            MiddleLeft=boardState[3],
                            MiddleMiddle=boardState[4],
                            MiddleRight=boardState[5],
                            BottomLeft=boardState[6],
                            BottomMiddle=boardState[7],
                            BottomRight=boardState[8])
def test_user_transformer_returns_user_obj_with_correct_attributes(user_data):
    games = [Game(appid=10, playtime=4600), Game(appid=20, playtime=2000)]
    stats = Csgo_stats(hours=1000,
                       total_kills=1000,
                       total_deaths=100,
                       defused_bombs=1000,
                       planted_bombs=1000,
                       money_earned=1000,
                       mvps=1000,
                       total_wins=1000,
                       knife_kills=1000,
                       shots_fired=1000,
                       shots_hit=1000,
                       rescued_hostages=507,
                       headshots=117038,
                       weapons_donated=8067,
                       dominations=3711,
                       revenges=317,
                       broken_windows=98,
                       gun_stats=gun_stats_obj)

    user = User_transformer().transform_user(user_data, games, stats)

    assert user.name == 'Lixard'
    assert user.img == 'https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/4a/4ad45031967e52ce05f28c7f5591227e66715c5d_full.jpg'
    assert user.url == 'https://steamcommunity.com/profiles/76561198066000502/'
    assert user.created == 1340730740
    assert user.games == games
    assert user.csgo_stats == stats
def user(gun_stats):
    return User(
        name='Lixard',
        img='https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/4a/4ad45031967e52ce05f28c7f5591227e66715c5d_full.jpg',
        url='https://steamcommunity.com/profiles/76561198066000502/',
        created=1340730740,
        games=[
            Game(appid=10, playtime=82),
            Game(appid=80, playtime=0),
            Game(appid=100, playtime=0),
            Game(appid=240, playtime=98)
        ],
        rating_calc=Rating_calc(),
        csgo_stats=Csgo_stats(
            defused_bombs=717,
            hours=5272693,
            knife_kills=1177,
            money_earned=278525408,
            mvps=29980,
            planted_bombs=2732,
            shots_fired=2231475,
            shots_hit=552856,
            total_deaths=103202,
            total_kills=214095,
            total_wins=56101,
            rescued_hostages=507,
            headshots=117038,
            weapons_donated=8067,
            dominations=3711,
            revenges=317,
            broken_windows=98,
            gun_stats=gun_stats
        )
    )
def server_command(gid, iid, pid, command, arguments):
  """ Performs the desired server command.

  Args:
    gid: The game id of the Game model for this operation.
    iid: The instance id of the GameInstance model for
      this operation.
    pid: The player id of the requesting player.
    command: The key identifying the command to execute.
    arguments: JSON representation of arguments to the command.

  If the gid and iid specify a valid game instance model it will be
  passed to the server command. In the case that the iid is empty or
  refers to a game instance that doesn't exist, a game model will be
  used. Most commands will fail if passed a game model instead of a
  game instance, but some are indifferent to the model passed to
  them.

  Unless the dynamic property do_not_put has been set to False, this
  will put the database model after the command has been
  performed. This means that server commands do not need to make
  intermediate puts of the instance model passed to them.

  Returns:
    A tuple of the model used in the server command's execution and a
    two item dictionary:
      'type': The requested command key.
      'contents': A Python value of the response value of the
        command. This varies among server commands but must always be
        able to be encoded to JSON.

  Raises:
    ValueError if the game id or player id is invalid.
    ValueError if the arguments json cannot be parsed.
    ValueError if command is not a known server command.
  """
  utils.check_gameid(gid)
  player = utils.check_playerid(pid)
  model = None
  if iid:
    model = utils.get_instance_model(gid, iid)
  if model is None:
    model = utils.get_game_model(gid)
    if model is None:
      model = Game(key_name = gid, instance_count = 0)

  arguments = simplejson.loads(arguments)
  reply = ''

  if command in command_dict:
    reply = command_dict[command](model, player, arguments)
    if 'do_not_put' not in model.dynamic_properties() or not model.do_not_put:
      model.put()
  else:
    raise ValueError("Invalid server command: %s." % command)

  if not isinstance(reply, list):
    reply = [reply]
  return model, {TYPE_KEY : command, CONTENTS_KEY: reply}
Exemple #18
0
 def post(self):
     game = Game()
     try:
         game.save_to_db()
         return {'id': game.id, 'message': 'Game has been created'}, 201
     except Exception as e:
         logger.error(e)
         return {'message': 'An error occurred creating game'}, 500
def test_game_to_json_returns_json():
    expected = {
        'appid': 10,
        'playtime': 1000
    }

    game = Game(appid=10, playtime=1000)
    result = game.to_json()

    assert result == expected
Exemple #20
0
    def cancel_game(self, request):
        """Cancel an unfinished game."""
        game = get_by_urlsafe(request.urlsafe_game_key, Game)
        if not game:
            raise endpoints.NotFoundException('Game not found!')
        if game.game_over:
            raise endpoints.ForbiddenException('Illegal action: Can\'t cancel a completed game!')

        Game.cancel_game(game)
        return game.to_form('Game has been canceled!')
Exemple #21
0
 def CreateNewGameIfAbsent(game_id):
     logging.info("Creating new game with id %d" % game_id)
     game_key = self.GetGameKeyName(game_id)
     if Game.get_by_key_name(game_key) is None:
         game = Game(key_name=game_key, owner=user)
         game.SetWindowLatLon(0, 0)
         self.AddPlayerToGame(game, user)
         self.PutGame(game, True)
         return game
     return None
Exemple #22
0
 def __init__(self, window, memes_enabled, rows_updated_per_frame,
              meteor_spawn_rate, name):
     # setup stuff
     self.game = Game(SCREEN_WIDTH // TILE_SIZE_IN_PIXELS, 256,
                      memes_enabled, rows_updated_per_frame,
                      meteor_spawn_rate, name)
     self.window = window
     self.held_keys = set()
     self.held_mouse_buttons = set()
     self.name = name
Exemple #23
0
def game(gameId):
    if session.get("username", None) == None:
        flash("Need to login")
        return redirect("/index")

    item = controller.getGame(gameId)
    if item == None:
        flash("That game does not exist.")
        return redirect("/index")

    boardState = controller.getBoardState(item)
    result = controller.checkForGameResult(boardState, item,
                                           session["username"])

    if result != None:
        if controller.changeGameToFinishedState(item, result,
                                                session["username"]) == False:
            flash("Some error occured while trying to finish game.")

    game = Game(item)
    status = game.status
    turn = game.turn

    if game.getResult(session["username"]) == None:
        if turn == game.o:
            turn += " (O)"
        else:
            turn += " (X)"

    gameData = {
        'gameId': gameId,
        'status': game.status,
        'turn': game.turn,
        'board': boardState
    }
    gameJson = json.dumps(gameData)

    return render_template("play.html",
                           gameId=gameId,
                           gameJson=gameJson,
                           user=session["username"],
                           status=status,
                           turn=turn,
                           opponent=game.getOpposingPlayer(
                               session["username"]),
                           result=result,
                           TopLeft=boardState[0],
                           TopMiddle=boardState[1],
                           TopRight=boardState[2],
                           MiddleLeft=boardState[3],
                           MiddleMiddle=boardState[4],
                           MiddleRight=boardState[5],
                           BottomLeft=boardState[6],
                           BottomMiddle=boardState[7],
                           BottomRight=boardState[8])
def bulk_analyse(engine, session, act_game):
    start_time = monotonic()

    # times = [0.010, 0.020, 0.050, 0.100, 0.200, 0.500, 1.000, 2.000, 5.000]
    times = [0.001, 0.001, 0.001, 0.010, 0.001, 0.001, 0.001, 0.001, 0.001]
    # times = [0.010, 0.020, 0.050, 0.100, 0.200, 0.500, 1.000, 0.001, 0.001]
    depths = [1, 1]
    # depths = [17, 20]
    n = 5

    # Get the intial board of the game
    board = act_game.board()

    print(act_game.headers["Event"] + " / " + act_game.headers["White"] +
          " - " + act_game.headers["Black"] + "  " +
          act_game.headers["Result"] + " / " + act_game.headers["Date"])

    db_game = Game(event=act_game.headers["Event"],
                   site=act_game.headers["Site"],
                   date=datetime.strptime(act_game.headers["Date"],
                                          '%Y.%m.%d').date(),
                   round=act_game.headers["Round"],
                   white=act_game.headers["White"],
                   black=act_game.headers["Black"],
                   whiteelo=(int(act_game.headers["WhiteElo"]) if
                             act_game.headers["WhiteElo"].isdigit() else None),
                   blackelo=(int(act_game.headers["BlackElo"]) if
                             act_game.headers["BlackElo"].isdigit() else None),
                   result=act_game.headers["Result"])

    print(db_game)

    # Iterate through all moves and play them on a board.
    prev_score = 0
    best_moves_b = []
    for ply_number, mv in enumerate(act_game.mainline_moves(), start=1):
        for i in range(0, n):
            db_mv, temp_best_moves_b = chess_moves.compute_move(
                engine, board, mv, ply_number, times, depths, prev_score,
                best_moves_b)
            db_game.moves.append(db_mv)
            print(db_mv)
        prev_score = db_mv.score
        best_moves_b = temp_best_moves_b
        # push actual move to the board again
        board.push(mv)

    db_game.length = int(ply_number)
    session.add(db_game)
    session.commit()

    runtime = monotonic() - start_time
    print("total runtime:", runtime)
Exemple #25
0
def CreateGame():
    if request.form['republic_home_id'] == request.form['republic_away_id']:
        return jsonify({'error': 'Dois times iguais foram selecionados'}), 400
    game = Game(
        republic_home_id=request.form['republic_home_id'],
        republic_away_id=request.form['republic_away_id'],
        time=request.form['time'],
        place=request.form['place'],
    )
    db.session.add(game)
    db.session.commit()
    return jsonify(game.toJSON()), 201
    def get_all_games(self, request):
        """Returns all games"""

        if request.active_only:
            games = Game.query(Game.game_over == False)
        else:
            games = Game.query()

        if games.count() >= 1:
            return AllGamesForm(games=[game.to_form("n/a") for game in games])
        else:
            raise endpoints.NotFoundException('No games found')
Exemple #27
0
def create_game():
    user = request.form.get('user')
    ps = PlayerSerialzer()
    cs = CardSerializer()
    if user not in player_map:
        return jsonify({"status_code": "400", "msg": "player not found"})

    player = player_map[user]
    global total_game
    # set up game
    game = Game(total_game)
    game.shuffle_deck()
class TestGame(unittest.TestCase):
    def setUp(self):
        self.player_rock = Player("Hayley", "rock")
        self.player_paper = Player("Aly", "paper")
        self.player_scissors = Player("Mel", "scissors")

        self.game1 = Game(self.player_rock, self.player_scissors)

    def test_has_players(self):
        self.assertEqual(self.player_rock, self.game1.player1)
        self.assertEqual(self.player_scissors, self.game1.player2)

    def test_rps_game__player1_wins__with_rock(self):
        result = self.game1.rps_game(self.player_rock.choice,
                                     self.player_scissors.choice)
        self.assertEqual("Player 1 wins!!", result)

    def test_rps_game__player1_wins__with_scissors(self):
        result = self.game1.rps_game(self.player_scissors.choice,
                                     self.player_paper.choice)
        self.assertEqual("Player 1 wins!!", result)

    def test_rps_game__player1_wins__with_paper(self):
        result = self.game1.rps_game(self.player_paper.choice,
                                     self.player_rock.choice)
        self.assertEqual("Player 1 wins!!", result)

    def test_rps_game__player2_wins__with_rock(self):
        result = self.game1.rps_game(self.player_scissors.choice,
                                     self.player_rock.choice)
        self.assertEqual("Player 2 wins!!", result)

    def test_rps_game__player2_wins__with_scissors(self):
        result = self.game1.rps_game(self.player_paper.choice,
                                     self.player_scissors.choice)
        self.assertEqual("Player 2 wins!!", result)

    def test_rps_game__player2_wins__with_paper(self):
        result = self.game1.rps_game(self.player_rock.choice,
                                     self.player_paper.choice)
        self.assertEqual("Player 2 wins!!", result)

    def test_rps_game__draw_with_rock(self):
        result = self.game1.rps_game(self.player_rock.choice,
                                     self.player_rock.choice)
        self.assertEqual("Draw!!", result)

    def test_rps_game__draw_with_scissors(self):
        result = self.game1.rps_game(self.player_scissors.choice,
                                     self.player_scissors.choice)
        self.assertEqual("Draw!!", result)

    def test_rps_game__draw_with_paper(self):
        result = self.game1.rps_game(self.player_paper.choice,
                                     self.player_paper.choice)
        self.assertEqual("Draw!!", result)
Exemple #29
0
 def test_game_result_ordering(self):
     game = Game()
     team_a = Team("A 0")
     team_b = Team("B 0")
     team_c = Team("c 0")
     team_a.score = 0
     team_b.score = 3
     team_c.score = 3
     # Ensure team ordering follows through to team list sorting
     game.teams = {"A": team_a, "B": team_b, "c": team_c}
     assert str(game.results()) == str([team_b, team_c, team_a])
     team_b.name = "d"
     game.teams["B"].name = "d"
     assert str(game.results()) == str([team_c, team_b, team_a])
def add_game(user: int, user_char: str, opponent: str, opponent_char: str,
             stage: str, win: bool, user_stock: int, opponent_stock: int):
    """
    validate users exist and are not the same
    create player matches and id
    create game obj and add to db

    :param user: id of user
    :param user_char: character used by user
    :param opponent: email of opponent
    :param opponent_char: character used by opponent
    :param stage: stage game was played on
    :param win: did user win
    :param user_stock: how many stocks did user have at match end
    :param opponent_stock: how many stocks did opponent have at match end
    :return: game obj
    """
    if user is opponent:
        raise UserIsOpponent
    usr = users_collection.find_one({ID: user})
    if usr is None:
        raise UserNotFound(user)
    opp = users_collection.find_one({EMAIL: opponent})
    if opp is None:
        raise UserNotFound(opponent)

    # generate random match_up id
    _id = 0
    while True:
        _id = random.randint(0, 999999999)
        m = games_collection.find_one({ID: _id})
        if m is None:
            break
    # create games with user and opponent data
    user_match = PlayerMatch(user, usr[EMAIL], usr[TAG], user_char, win,
                             user_stock, True)
    opponent_match = PlayerMatch(opp[ID], opp[EMAIL], opp[TAG], opponent_char,
                                 not win, opponent_stock)

    # add match up to db
    new_game = Game(_id, stage, [user_match, opponent_match])
    games_collection.insert_one(new_game.dict())
    # add match up id to user and opponent's match up arrays
    users_collection.update_many({ID: {
        "$in": [user, opp[ID]]
    }}, {"$push": {
        GAMES: _id
    }})
    return new_game
Exemple #31
0
async def game(websocket, path):
    if not get_game():
        set_game(Game())
        LOGGER.info("Game code is %s.", get_game().code)

    async for message in websocket:
        data = json.loads(message)
        LOGGER.info("Received event. Data: %s.", data)

        response = None
        can_handle = False
        event_action = data.get("action", None)
        for action, handler in HANDLERS.items():
            if event_action == action.value:
                can_handle = True
                try:
                    response = await handler(websocket, path, data)
                except (GameException, HandlingException) as e:
                    LOGGER.info("Game or handling error: %s", str(e))

        if not can_handle:
            LOGGER.info("Cannot handle action of type '%s'", str(event_action))

        if response:
            await websocket.send(response)
Exemple #32
0
 def cancel_game(self, request, user):
     """Cancels game in progress"""
     if not user:
         raise endpoints.NotFoundException(
                 'A User with that name does not exist!')
     
     #Check to see if use is in a live game
     ingamecheck=Game.query(Game.user==user.key).get()
     if hasattr(ingamecheck, "user")==True:
         if ingamecheck.game_over==False:
             setattr(ingamecheck, "canceled_game", True)
             setattr(ingamecheck, "game_over", True)
             ingamecheck.put()
             return StringMessage1 \
             (message='User {} has canceled the game. Play again soon!!'. \
                 format(request.user_name))
         
         else:
             return StringMessage1 \
             (message='User {}, no active game, cancellation not possible.' \
                 .format(request.user_name))
     
     else:
         raise endpoints.NotFoundException(
                 'User {} does not have any games to cancel!'. \
                 format(request.user_name))
def start_multiplayer():
    '''
    Makes two *Player* objects and starts the multiplayer mode.

    Returns
    -------
    None
    '''

    players = Ui.get_inputs(["First player's name", "Second player's name"],
                            "Please provide your names")
    player1 = Player(players[0])
    player2 = Player(players[1])

    gameplay = Game(player1, player2)
    gameplay.start_game()
Exemple #34
0
def overall_results(team):
  games = Game.query(Game.team == team).order(Game.date).fetch(100)
  game_votes = []
  player_votes = {}

  for game in games:
    results = game_results(game)
    if not results:
      continue

    if player_votes.has_key(results.three):
      player_votes[results.three].threes +=1
      player_votes[results.three].total += 3 * game.weight
    else:
      player_votes[results.three] = \
        PlayerOverallVotes(player=results.three, threes=1, total=3*game.weight)

    if player_votes.has_key(results.two):
      player_votes[results.two].twos +=1
      player_votes[results.two].total +=2 * game.weight
    else:
      player_votes[results.two] = \
        PlayerOverallVotes(player=results.two, twos=1, total=2*game.weight)

    if player_votes.has_key(results.one):
      player_votes[results.one].ones +=1
      player_votes[results.one].total +=1 * game.weight
    else:
      player_votes[results.one] = \
        PlayerOverallVotes(player=results.one, ones=1, total=game.weight)

    game_votes.append(results)

  sorted_votes = sorted(player_votes.items(), key=lambda p: -p[1].ranking_points())
  return OverallResults(player_votes=[r[1] for r in sorted_votes], game_votes=game_votes)
 def deactivate_game(self, request):
     """Sets the active flag on a game record to false"""
     self.check_auth()
     game = Game.deactivate_game(request.game_key)
     form = GameFunctionForm()
     form.game_key = game.key.urlsafe()
     form.true_or_false = game.game_active
     return form
Exemple #36
0
    def leave_game(self, player_name):
        player = Player.get_player(player_name)
        game_id = player.game_id

        game = Game.get_game(game_id)
        if game.remove_player(player_name):
            return self.redirect('/')
        else:
            return self.response.http_status_message(404)
Exemple #37
0
 def get(self):
     
     games = Game.query().fetch()
     context = {
         'games': games,
     }
     
     template = JINJA_ENVIRONMENT.get_template('templates/load_games.html')
     self.response.write(template.render(context))
Exemple #38
0
def cache_average_attempts():
    games = Game.query(Game.game_over is False).fetch()
    if games:
        count = len(games)
        total_guesses_remaining = sum([game.guesses_remaining
                                       for game in games])
        average = float(total_guesses_remaining) / count
        memcache.set(MEMCACHE_GUESSES_REMAINING,
                     'The average guesses remaining is {:.2f}'.format(average))
def new_instance(gid, iid_prefix, pid, make_public = False):
  """ Create a new instance of the specified game.

  Args:
    gid: The game id of the Game parent of the new instance.
    iid_prefix: The desired instance id. If no instance has been made
      with this name before, then this will be the instance id of the
      newly created instance. However, since instance ids must be
      unique, the actual instance id will likely be iid_prefix with a
      number suffix.
    pid: The id of the first player and leader of the game.
    make_public: A boolean indicating whether this instance should
      be able to be seen and joined by anyone.

  The instance id will start with iid_prefix, but could have any
  suffix. If the parent Game object does not exist, it will
  automatically be created.

  Returns:
    A tuple of the newly created instance and an instance lists
    dictionary (see get_instance_lists_as_dictionary).

  Raises:
    ValueError if the gameid or player id are invalid.
  """
  utils.check_gameid(gid)
  player = utils.check_playerid(pid)
  game = Game.get_by_key_name(gid)
  if game is None:
    game = Game(key_name = gid, instance_count = 0)

  if not iid_prefix:
    iid_prefix = player + 'instance'
  instance = game.get_new_instance(iid_prefix, player)

  instance_lists = get_instances_lists_as_dictionary(game, player)
  instance_lists['joined'].append(instance.key().name())
  if make_public:
    instance.public = True
    instance_lists['public'].append(instance.key().name())
  instance.put()
  game.put()

  return instance, instance_lists
    def get_user_games(self, request):
        """Returns all active games of the user"""
        player = User.query(User.name == request.player_name).get()

        games = Game.query(Game.state == GameState.ACTIVE)
        games = games.filter(ndb.OR(Game.player_one == player.key,
                                    Game.player_two == player.key))

        return ActiveGamesForm(
            games=[g.key.urlsafe() for g in games])
Exemple #41
0
 def CreateNewGameIfAbsent(game_id):
   logging.info("Creating new game with id %d" % game_id)
   game_key = self.GetGameKeyName(game_id)
   if Game.get_by_key_name(game_key) is None:
     game = Game(key_name=game_key, owner=user)
     game.SetWindowLatLon(0, 0)
     self.AddPlayerToGame(game, user)
     self.PutGame(game, True)
     return game
   return None
 def new_game(self, request):
     """Creates new game"""
     user = User.query(User.name == request.user_name).get()
     if not user:
         raise endpoints.NotFoundException(
                 'A User with that name does not exist!')
     try:
         game = Game.new_game(user.key, request.card_cnt)
     except ValueError, err:
         raise endpoints.BadRequestException(str(err))
Exemple #43
0
 def new_game(self, request):
     """Creates new game"""
     user = self._getUser()
     if request.player2_name:
         player2 = User.query(User.name == request.player2_name).get()
         if not player2:
             raise endpoints.NotFoundException(
                 'A User with that name does not exist!')
         # Check that the user isn't playing against themselves.
         if player2.name == user.name:
             raise endpoints.ConflictException(
                 'You are already in the game!')
     else:
         player2 = None
     board = [0] * 9
     'In many instances of tic tac toe, X goes first. House rules.'
     if request.isPlayer1_X:
         isPlayer1_turn = True
     else:
         isPlayer1_turn = False
     if not user:
         raise endpoints.NotFoundException(
             'A User with that name does not exist!')
     if request.player2_name:
         game = Game.new_game(
             user.key,
             board,
             request.isPlayer1_X,
             isPlayer1_turn,
             player2.key)
     else:
         game = Game.new_game(
             user.key,
             board,
             request.isPlayer1_X,
             isPlayer1_turn)
     user.gameKeysPlaying.append(game.key.urlsafe())
     user.put()
     if request.player2_name:
         if game.player2 and game.player1 != game.player2:
             player2.gameKeysPlaying.append(game.key.urlsafe())
             player2.put()
     return game.to_form('Have fun playing Tic-Tac-Toe!')
Exemple #44
0
 def LoadFromDatastore(self, key):
   """Load the game from the database.  Sets self.game, returns true if
   self.game was successfully set.  If false, self.game was not set."""
   logging.info("Getting game from datastore.")
   game = Game.get_by_key_name(key)
   if game:
     self.game = game
     return True
   else:
     return False
Exemple #45
0
 def _cache_average_attempts():
     """Populates memcache with the average moves remaining of Games."""
     games = Game.query(Game.game_over == False)
     if games:
         count = games.count()
         total_attempts_remaining = sum([game.attempts_remaining
                                         for game in games])
         average = total_attempts_remaining / float(count)
         memcache.set(MEMCACHE_MOVES_REMAINING,
                      'The average moves remaining is {:.2f}'.format(average))
 def cancel_game(self, request):
     """
     Sets the active flag on a game record to false and sets the
     status to 'cancelled'
     """
     self.check_auth()
     game = Game.cancel_game(request.game_key)
     form = GameFunctionForm()
     form.game_key = game.key.urlsafe()
     form.true_or_false = game.game_active
     return form
 def _cache_average_attempts():
     """Populates memcache with the average moves remaining of Games"""
     games = Game.query(Game.finished).fetch()
     if games:
         count = len(games)
         total_attempts_done = sum([game.attempts_done
                                    for game in games])
         average = float(total_attempts_done) / count
         memcache.set(MEMCACHE_MOVES_DONE,
                      'The average moves done for finished games is {:.2f}'
                      .format(average))
Exemple #48
0
  def get(self, game_id=None):
    if not game_id:
      template = jinja_environment.get_template("templates/email_list.html")
      games = Game.query().order(Game.date).fetch(100)
      self.response.out.write(template.render({'games':games}))
      return

    game = Game.get_by_id(int(game_id))
    if not game:
      self.response.out.write("Error: invalid game ID")
      logging.error("Invalid game ID: " + str(game_id))
      return

    players = Player.query().order(Player.name).fetch(100)
    playing = [p for p in players if p.key in game.players]
    not_playing = [p for p in players if p.key not in game.players]

    template = jinja_environment.get_template("templates/send_emails.html")
    args = {'playing':playing,'not_playing':not_playing,'game':game}
    self.response.out.write(template.render(args))
Exemple #49
0
  def post(self):
    game_id = self.request.get("game")
    voter_id = self.request.get("player")

    voter = Player.get_by_id(int(voter_id))
    game = Game.get_by_id(int(game_id))

    value = base64.urlsafe_b64encode(os.urandom(16))
    token = Token(value=value, voter=voter.key, game=game.key, used=False)
    token.put()
    url = "http://vote.ouarfc.co.uk/vote/" + value
    self.response.out.write(url)
Exemple #50
0
  def post(self):
    opponent = self.request.get("opponent")
    date_string = self.request.get("date")
    venue = self.request.get("venue")
    player_id_strings = self.request.get_all("players")
    team = Team.getTeam(self.request.get("team"))
    weight = float(self.request.get("weight"))

    date_tokens = date_string.split("/")
    if len(date_tokens) == 1:
      date_tokens = date_string.split("-")
    if int(date_tokens[0]) < 100:
      date_tokens.reverse()
    date = datetime.date(int(date_tokens[0]), int(date_tokens[1]), int(date_tokens[2]))

    game = Game(opponent=opponent, date=date, venue=venue, team=team, weight=weight)
    player_keys = [ndb.Key('Player', int(pid)) for pid in player_id_strings]
    game.players = player_keys
    game.put()

    template = jinja_environment.get_template("templates/game_added.html")
    self.response.out.write(template.render({}))
Exemple #51
0
    def new_game(self, request):
        '''Creates new game'''
        user = User.query(User.name == request.user_name).get()
        if not user:
            raise endpoints.NotFoundException(
                'A User with that name does not exist!')
        game = Game.new_game(user.key)

        # Use a task queue to update the plant status.
        # This operation is not needed to complete the creation of a new game
        # so it is performed out of sequence.
        # taskqueue.add(url='/tasks/cache_plant_status')
        return game.to_form()
Exemple #52
0
    def get_games(self, request):
        '''Return all the games created by the user.'''
        user_email = endpoints.get_current_user().email()
        user = User.query(User.email == user_email).get()
        if not user:
            raise endpoints.NotFoundException(
                'Impossible to get scores if account has no email!')
        user_key = user.key

        games = Game.query(Game.user == user_key, Game.game_over == False)
        logging.debug('Number of games retrieved: %s', games.count())
        game_forms = GameForms(items=[game.to_form() for game in games])
        return game_forms
Exemple #53
0
  def get(self, game_id):
    game = Game.get_by_id(int(game_id))
    if not game:
      self.response.out.write("Error: invalid game ID")
      logging.error("Invalid game ID: " + str(game_id))
      return

    voters = Token.query(ndb.AND(Token.game == game.key, Token.used == True)).fetch(100)
    non_voters = Token.query(ndb.AND(Token.game == game.key, Token.used == False)).fetch(100)

    template = jinja_environment.get_template('templates/voters.html')
    params = {'voters':voters,'non_voters':non_voters,'game':game}
    self.response.out.write(template.render(params))
def get_instance_lists(gid, iid, pid):
  """ Return the instances that a player has been invited to and joined.

  Args:
    gid: The game id of the Game object that this method targets.
    iid: The instance id of the Game Instance object that this
      method targets.
    pid: A string containing the requesting player's email address.

  The gid and pid must be valid, but the iid can be blank. This is
  because a player must be able to query for lists of instances
  without being in one.

  Returns:
    A tuple containing a database model and a dictionary of instance
    lists.  The database model will be a Game Instance if the gid and
    iid parameters specify a valid GameInstance, otherwise the model
    will be a Game.  Instance lists are returned in the same format
    as get_instance_lists_dictionary.

  Raises:
    ValueError if the game id or player id are invalid.
  """
  utils.check_gameid(gid)
  player = utils.check_playerid(pid)
  model = game = utils.get_game_model(gid)
  if game is None:
    game = Game(key_name = gid, instance_count = 0)
    game.put()
    model = game
  elif iid:
    instance = utils.get_instance_model(gid,iid)
    if instance:
      model = instance
  instance_lists = get_instances_lists_as_dictionary(game, player)
  return model, instance_lists
Exemple #55
0
    def get(self):
        """Send a reminder email to each User that has unfinished games.
        Called every hour using a cron job"""
        logging.info('[Cron job] Started: SendReminderEmail')

        app_id = app_identity.get_application_id()
        num_sent = 0
        for user in User.query(User.email != None):
            games = Game.query(Game.game_over == False,
                               Game.user == user.key)
            urlsafes = [game.key.urlsafe() for game in games]
            if len(urlsafes) > 0:
                self._send_email(app_id, user, urlsafes)
                num_sent += 1
        logging.info('[Cron job] Finished: SendReminderEmail. Sent %s emails',
                     num_sent)
Exemple #56
0
 def get(self):
     """Send a reminder email to each User with an email about games.
     Called every hour using a cron job"""
     app_id = app_identity.get_application_id()
     users = User.query(User.email != None)
     for user in users:
         games = Game.query(Game.user == user.key)
         for game in games:
             if game.game_over == False:
                 subject = 'This is a reminder for your hangman game!'
                 body = "Hello {}, Come play hangman!".format(user.name)
                 # This will send test emails, the arguments to send_mail are:
                 # from, to, subject, body
                 mail.send_mail('noreply@{}.appspotmail.com'.format(app_id),
                                user.email,
                                subject,
                                body)
Exemple #57
0
 def get_user_game(self, request, user):
     """Return all User's active games"""
     if not user:
         raise endpoints.NotFoundException(
                 'A User with that name does not exist!')
     
     ingamecheck=Game.query(Game.user==user.key).get()
     if not ingamecheck:
         raise endpoints.NotFoundException('User does not have any games.')
     
     if ingamecheck.game_over == False:
         return ingamecheck.to_form \
         ('Here is the status of your active game.')
     
     else:
         raise endpoints.NotFoundException \
         ('No active game found for user. Please try another user name')
    def get_user_games(self, request):
        """Return all active games of given user."""
        user = User.query(User.name == request.user_name).get()
        if not user:
            raise endpoints.NotFoundException(
                    'A User with that name does not exist!')

        # Return only active games (not finished)
        games = Game.query(Game.user == user.key)\
            .filter(Game.finished == False)

        if games is None:
            raise endpoints.NotFoundException(
                    'User has no active games!')
            
        return UserGamesResponseForm(user_name=user.name,
                                     games=[gam.to_form('') for gam in games])
Exemple #59
0
 def get_user_games(self, request):
     """Return all user's active games
     Args:
         request: The USER_REQUEST objects, which includes a users
             chosen name and an optional email.
     Returns:
         GameForms: collection of GameForm with information about each game.
     Raises:
         endpoints.BadRequestException: If no user for the user_name exists.
     """
     if request.user_name is None:
         raise endpoints.BadRequestException('You must enter a user name.')
     user = User.query(User.name == request.user_name).get()
     if not user:
         raise endpoints.BadRequestException('The user {} does not exist!.'.format(request.user_name))
     games = Game.query(Game.user == user.key).filter(Game.game_over == False)
     return GameForms(items=[game.to_form('') for game in games])