Ejemplo n.º 1
0
def first_input():
    s = [
        "# -------------- VM  version 1.1 ------------- #",
        "#                                              #",
        "# 42 / filler VM Developped by: Hcao - Abanlin #",
        "#                                              #",
        "# -------------------------------------------- #"
    ]
    for i in s:
        str = input()
        if i != str:
            sys.exit(1)
    p1 = input().split()
    if p1[0] != "launched":
        sys.exit(1)
    player_1 = Player(p1[1])  # Initialise the player_1 name and object
    s1 = input()
    s1_check = "$$$ exec p1 : [" + player_1.player_name + "]"
    player_1.get_number_of_player(s1_check[10])
    if s1_check != s1:
        sys.exit(1)
    p2 = input().split()
    if p2[0] != "launched":
        sys.exit(1)
    player_2 = Player(p2[1])  # Initialise the player_1 name and object
    s2 = input()
    s2_check = "$$$ exec p2 : [" + player_2.player_name + "]"
    player_2.get_number_of_player(s2_check[10])
    if s2_check != s2:
        sys.exit(1)
    return player_1, player_2
Ejemplo n.º 2
0
 def setup_method(self, method):
     team1 = Team(0, Player("Alex"), Player("Thibaud"))
     team2 = Team(1, Player("Marie"), Player("Veltin"))
     distributor = Distributor()
     referee = Referee()
     self.game_night = Game(team1, team2, distributor, referee, verbosity=1)
     self.commentator = GameCommentator(1)
Ejemplo n.º 3
0
def main():
    p1 = Player("Connor", 0)
    p2 = Player("CPU", 1)
    system = System([p1, p2])
    while system.noPlayerIsOut():
        print(system.statusMsg())
        system.playHand()
        print(system.statusMsg())
Ejemplo n.º 4
0
 def setup_method(self, method):
     team1 = Team(0, Player("Alex"), Player("Thibaud"))
     team2 = Team(1, Player("Marie"), Player("Veltin"))
     deck = Deck()
     distributor = Distributor()
     referee = Referee()
     self.round = Round(0, team1, team2, deck, distributor,
                        referee, seed=36)
Ejemplo n.º 5
0
 def test_referee_should_compute_team_score(self):
     team = Team(0, Player(), Player())
     cards = [Card("C", "E"), Card("C", "N"), Card("C", "J")]
     trick = Trick(cards).to_ranked("C")
     team.get_cards(trick)
     assert self.referee.count_team_points(team) == 34
     team.started = True
     assert self.referee.count_team_points(team) == 0
Ejemplo n.º 6
0
def main():
    """ run the game """
    # Board init
    window_width, window_height, tile_size = [int(i.strip("")) for i in input("Enter window width, height, and tile size:\n").split(" ")]
    board = Board(window_width, window_height, tile_size)

    # Players init
    player1 = Player()
    play_AI = input("Do you want to player with AI? [y/n]: ")
    if play_AI == 'y':
        minimax_depth = int(input("\nEnter AI player maximum depth for minimax: "))
        branch_factor = int(input("Enter AI player branch factor: "))
        player2 = AI(minimax_depth, branch_factor)
    else:
        player2 = Player()

    # Run game
    board.window = GraphWin('Tic Tac Toe', board.window_height, board.window_width)
    board.draw_grid()
    print("Begin Game!")
    
    turn = 0
    win = False
    while not win:
        if turn % 2 == 0:
            move = player1.get_move(board)
        else:
            if play_AI == 'y':
                start = time()
                # move = player2.get_move(board, depth=player2.minimax_depth, branch_factor=player2.branch_factor)
                move = player2.get_move_iterative_deepening(board, player2.minimax_depth, player2.branch_factor, 5)
                end = time()
                print("Time elapsed for move {} is {:2f}s".format(turn + 1, end - start))
            else:
                move = player2.get_move(board)
        changed = board.update_board(move)
        win, pos = board.check_win(move)
        
        if turn == 6:
            breakpoint()

        if win:
            board.draw_winning_line(pos[0], pos[1])
            break

        if not board.check_full():
            turn += 1
        else:
            break

    if board.check_full() is False:
        print("Player {} wins!".format(2 - int(turn % 2 == 0)))
    else:
        print("The game is a tie!")

    board.window.getMouse()
    board.window.close()
Ejemplo n.º 7
0
    def __init__(self):
        #fix: rename and add javascript client
        self.engine_rpc = FibonacciRpcClient()
        self.pp = pprint.PrettyPrinter(indent=4)

        self.players = [
            Player("p1", 'player-1-queue'),
            Player("p2", 'player-2-queue')
        ]
Ejemplo n.º 8
0
 def setup_method(self, method):
     team1 = Team(0, Player("Alex"), Player("Thibaud"))
     team2 = Team(1, Player("Marie"), Player("Veltin"))
     deck = Deck()
     distributor = Distributor()
     referee = Referee()
     self.game = Round(0, team1, team2, deck, distributor, referee)
     self.output = StringIO()
     self.commentator = RoundCommentator(1, stream=self.output)
Ejemplo n.º 9
0
    def __init__(self, n_players: int,
                 field_type: Union[QuadTree, TwoDTree],
                 duration: int,
                 max_speed: int,
                 max_vision: int) -> None:
        """Initializes a new ZombieTag Game objext with <n_players> humans and
        1 zombie at the start on a field <field_type>. This game has a duration
        <duration>. Each human has a maximum possible speed of <max_speed> and
        a maximum possible vision of <max_vision>.

        >>> tree = QuadTree((250, 250))
        >>> game = ZombieTag(10, tree, 5, 3, 4)
        >>> len(game._humans)
        10
        >>> all(name in game.field for name in game._zombies)
        True
        >>> all(name in game.field for name in game._humans)
        True
        >>> len(game._zombies.keys() & game._humans.keys())
        0
        >>> all(player._colour == 'green' for _, player in game._humans.items())
        True
        >>> len(game._zombies)
        1
        >>> game._zombies.popitem()[1]._colour
        'purple'
        """
        Game.__init__(self, field_type)
        self._duration = duration
        self._humans = {}
        self._zombies = {}

        lst_x = []
        lst_y = []

        while len(lst_x) < n_players + 1:
            random_x = random.randint(0, 500)
            random_y = random.randint(0, 500)

            if random_x not in lst_x or random_y not in lst_y:
                lst_x.append(random_x)
                lst_y.append(random_y)

        self._zombies['CS_POST'] = Player('CS_POST', max_vision, 1, self,
                                          'purple', (lst_x[-1], lst_y[-1]))
        self.field.insert('CS_POST', (lst_x[-1], lst_y[-1]))

        for i in range(n_players):
            new_player = Player(str(i), random.randint(0, max_vision),
                                random.randint(0, max_speed), self, 'green',
                                (lst_x[i], lst_y[i]))
            self._humans[str(i)] = new_player
            self.field.insert(str(i), (lst_x[i], lst_y[i]))

            self._humans[str(i)].select_enemy('CS_POST')
            self._zombies['CS_POST'].select_target(str(i))
Ejemplo n.º 10
0
    def __init__(self, purse):

        #store the new deck
        self.game_deck = Deck()

        #initialize player with a purse
        self.Player = Player(purse)

        #initialize computer player with a purse
        self.Computer = Player(purse)
Ejemplo n.º 11
0
    def add_players(self):
        """Create the players.

        Return an array of the players as objects with .draw methods.
        """
        player1 = Player(color=Colors.YELLOW,
                         start_x=self.max_x / 5 * 2,
                         controls=[ControlSet()])
        player1.images = PlayerImages(default=Images.get_path(r'seahorse.png'),
                                      size_x=self.player_size,
                                      size_y=self.player_size)
        player2 = Player(color=Colors.RED,
                         start_x=self.max_x / 5 * 4,
                         controls=[
                             ControlSet(up=pygame.K_j,
                                        down=pygame.K_k,
                                        left=pygame.K_h,
                                        right=pygame.K_l),
                             ControlSet(up=pygame.K_w,
                                        down=pygame.K_s,
                                        left=pygame.K_a,
                                        right=pygame.K_d)
                         ])
        player2.images = PlayerImages(default=Images.get_path(r'squid.png'),
                                      size_x=self.player_size,
                                      size_y=self.player_size)
        player3 = Player(color=Colors.BLUE,
                         start_x=self.max_x / 5,
                         controls=[
                             ControlSet(up=pygame.K_3,
                                        down=pygame.K_2,
                                        left=pygame.K_1,
                                        right=pygame.K_4)
                         ])
        player3.images = PlayerImages(default=Images.get_path(r'flounder.png'),
                                      size_x=self.player_size,
                                      size_y=self.player_size)
        player4 = Player(color=Colors.PURPLE,
                         start_x=self.max_x / 5 * 3,
                         controls=[
                             ControlSet(up=pygame.K_7,
                                        down=pygame.K_6,
                                        left=pygame.K_5,
                                        right=pygame.K_8)
                         ])
        player4.images = PlayerImages(
            default=Images.get_path(r'cuttlefish.png'),
            size_x=self.player_size,
            size_y=self.player_size)

        self.players = [player1, player2, player3, player4]
        for player in self.players:
            player.pos_y = self.ground_y - player.size_y / 2
            player.ground_y = self.ground_y
            player.max_x = self.max_x
Ejemplo n.º 12
0
 def __init__(self, players=None, buyIn=10000):
     self.game = PokerGame()
     if players == None:
         self.players = [Player("Nova", 0), Player("CPU", 1)]
     elif len(players) != 2:
         print("ERROR")
         sys.exit(1)
     else:
         self.players = players
     for p in self.players:
         p.chips = buyIn
Ejemplo n.º 13
0
 def test_gameplay_withDraw(self, mock_moves, mock_players):
     mock_moves.side_effect = [1,2,2,1]
     mock_players.side_effect = ['R', 'G']
     board = [["X", "X"],
              ["X", "X"]]
     board = Board(board)
     player = []
     colors = ['R', 'G', 'B', 'Y']
     player.append(Player(colors))
     player.append(Player(colors))
     self.assertEqual(board.gameplay(player), "DRAW")
def main():
    print_header()

    rolls = build_rolls()

    name = get_players_name()

    player1 = Player(name)
    player2 = Player("Bill the Computer")

    game_loop(player1, player2, rolls)
Ejemplo n.º 15
0
    def __init__(self, n_players: int,
                 field_type: Union[QuadTree, TwoDTree],
                 max_speed: int,
                 max_vision: int) -> None:
        """Intializes a new ElimnationTag Game object with <n_players> players
        on <field_type>. Each player has a maximum possible speed of <max_speed>
        and a maximum possible vision of <max_vision>.

        >>> tree = QuadTree((250, 250))
        >>> game = EliminationTag(10, tree, 3, 4)
        >>> len(game._players)
        10
        >>> all(name in game.field for name in game._players)
        True
        >>> items = game._players.items()
        >>> all(player._colour == 'random' for _, player in items)
        True
        """
        Game.__init__(self, field_type)
        self._players = {}

        lst_x = []
        lst_y = []

        while len(lst_x) < n_players:
            random_x = random.randint(0, 500)
            random_y = random.randint(0, 500)

            if random_x not in lst_x or random_y not in lst_y:
                lst_x.append(random_x)
                lst_y.append(random_y)

        player1 = Player('a', random.randint(0, max_vision),
                         random.randint(1, max_speed),
                         self, 'random', (lst_x[0], lst_y[0]))

        self.field.insert('a', (lst_x[0], lst_y[0]))
        self._players['a'] = player1

        for i in range(1, n_players, 1):
            name = (i+1)*'a'
            new_player = Player(name, random.randint(0, max_vision),
                                random.randint(1, max_speed),
                                self, 'random', (lst_x[i], lst_y[i]))
            self._players[name] = new_player
            self.field.insert(name, (lst_x[i], lst_y[i]))

            prev_name = i*'a'
            self._players[name].select_enemy(prev_name)
            self._players[prev_name].select_target(name)

        self._players[n_players*'a'].select_target('a')
        self._players['a'].select_enemy(n_players*'a')
Ejemplo n.º 16
0
 def setup(self):
     self.player_1 = Player()
     self.player_1.board.clear_screen()
     self.player_1.board.ship_placement()
     self.player_1.board.hide_board()
     self.player_1.board.clear_screen()
     input("Captain {}, your turn is complete. Please switch players and press any key ".format(self.player_1.name))
     self.player_1.board.clear_screen()
     self.player_2 = Player()
     self.player_2.board.clear_screen()
     self.player_2.board.ship_placement()
     self.player_2.board.hide_board()
     self.player_2.board.clear_screen()
     input("Captain {}, your turn is complete. Please switch players and press any key ".format(self.player_2.name))
Ejemplo n.º 17
0
def start_game():

    # initialize colors
    colors = ['R', 'G', 'B', 'Y']
    # create players
    players = []
    print("Choose player ", 1, " color: ")
    players.append(Player(colors))
    print("Choose player ", 2, " color: ")
    players.append(Player(colors))

    # initialize board
    board = Board()
    # play
    print(board.gameplay(players))
Ejemplo n.º 18
0
    def __init__(self):
        # Scoreboard
        self.score_board = ScoreBoard(position=(0, 260), dims=(1, 1))

        # Paddle A
        self.player_a = Player(pos=(-350, 0))

        # Paddle B
        self.player_b = Player(pos=(350, 0))

        # Write score
        self.score_board.score_write(self.player_a.score, self.player_b.score)

        # Ball
        self.Ball = Ball(position=(0, 0), dims=(1, 1), shape="circle")
Ejemplo n.º 19
0
    def add_player(self, balance):
        """Add a new player to the table.

        Args:
            balance: int, the initial balance of the player.
        """
        self._players.append(Player(balance))
Ejemplo n.º 20
0
 def start(self):
     self.player_1 = Player()
     self.player_2 = SmartRandom(self.get_color(), self.board)
     if self.player_1.color == 4:
         print('\nВы играете за БЕЛЫХ!\n')
         k = 1  # Определяет очередность хода
     else:
         print('\nВы играете за ЧЕРНЫХ!\n')
         k = 0  # Определяет очередность хода
     load('loading')
     print('x - Пустые черные клетки\nБ - белая шашка\nЧ - черная шашка\n'
           '\nh1 - поставить шашку в клетку h1'
           '\nb1->c2 - ход из клетки b1 в клетку c2\n'
           'd3->f5 - бой из клетки d3 через клетку e4 в клетку f5\n')
     print('Всё понятно?\n')
     input_()
     load('\nЗагружаю доску')
     self.board.render()
     print('  |----------- Давайте расставим шашки -----------|\n')
     self.fill(k)
     winner, log_ = self.game(k)
     if winner == 'w4' and self.player_1.color == 4 or winner == 'w3' and self.player_1.color == 3:
         print('\n  |' + 47*'*' + '|')
         print('  |------------------- ПОБЕДА! -------------------|')
         print('  |' + 47 * '*' + '|')
     else:
         print('\n  |----- Вы проиграли. Повезет в другой раз! -----|\n')
     try:
         self.log(log_)
     except IndexError:
         self.note.write('Случилась партия без ходов')
     self.end()
Ejemplo n.º 21
0
def simulate(numHands):
    card_cut_ptr = [random.randint(CUT_MIN, CUT_MAX)]
    draw_pile = Deck(NUM_DECKS)
    discard_pile = CardCollection()
    dealer = Dealer()
    player1 = Player()
    players = [player1]
    log = []

    for _ in range(numHands):

        # deal cards
        for _ in range(2):
            for p in players + [dealer]:
                p.add_card_to_hand(draw_pile.pop_a_card())

        for p in players + [dealer]:
            play_round(p, card_cut_ptr, draw_pile, discard_pile)

        for p in players:
            evaluate_round(p, dealer)

        log.append(p.wallet)

        clear_table(players + [dealer], discard_pile)

    return log
Ejemplo n.º 22
0
def countingGame():
    # TODO: you can change the three constants below and try playing against the computer
    # goalNumber: number where a player need to reach or pass to win
    # minStep: minimum increment when counting
    # maxStep: maximum increment when counting
    # Make sure the condition is met: goalNumber > maxStep > minStep
    minStep = 1
    maxStep = 3
    goalNumber = 10

    if goalNumber > maxStep > minStep:
        playerName = input("What is your name? ")

        # introduction and demo
        introduction.introduction()
        print()
        time.sleep(0.5)
        tutorial.runDemo()
        time.sleep(0.5)
        print()

        # create players
        player = Player(name=playerName, goalNumber=goalNumber)
        comp = Computer(goalNumber=goalNumber, minStep=minStep, maxStep=maxStep)

        # start Game
        gf.startGame(player=player, comp=comp, goalNumber=goalNumber, minStep=minStep, maxStep=maxStep)
        time.sleep(0.5)

        print()
        gf.restart(player=player, comp=comp, goalNumber=goalNumber, minStep=minStep, maxStep=maxStep)

    else:
        print("Make sure the condition is met: goalNumber > maxStep > minStep")
Ejemplo n.º 23
0
    def test_max_time_in_air(self):
        player = Player()
        new_platform_y_coordinate = 200
        last_platform_y_coordinate = 400

        upwards_time = player.max_jump_height / player.upwards_velocity
        max_y_coordinate = last_platform_y_coordinate - player.max_jump_height
        downwards_time = (new_platform_y_coordinate -
                          max_y_coordinate) / PhysicsEngine.gravity_pull
        got = player.max_time_in_air(new_platform_y_coordinate,
                                     last_platform_y_coordinate,
                                     PhysicsEngine.gravity_pull)
        self.assertEquals(
            upwards_time + downwards_time, got,
            "Should get the time it takes to jump and down onto the next platform"
        )
        print("START OF TEST")
        last_platform_y_coordinate = player.height + (player.max_jump_height *
                                                      .8)
        print(last_platform_y_coordinate - player.max_jump_height -
              player.height <= 0)
        upwards_time = (last_platform_y_coordinate -
                        player.height) / player.upwards_velocity
        max_y_coordinate = player.height
        downwards_time = (new_platform_y_coordinate -
                          max_y_coordinate) / PhysicsEngine.gravity_pull
        got = player.max_time_in_air(new_platform_y_coordinate,
                                     last_platform_y_coordinate,
                                     PhysicsEngine.gravity_pull)
        self.assertEquals(
            upwards_time + downwards_time, got,
            "Should account for the fact that the player hits the top of screen making the max_y_coordinte smaller"
        )
Ejemplo n.º 24
0
def players_list():
    num_players = define_number_of_players()
    players_list = []
    for total_players in range(num_players):
        name = input(f'\nWhat is your name player {total_players + 1}?\n')
        players_list.append(Player(name))
    return players_list
Ejemplo n.º 25
0
 def __init__(self, agent):
     self.agent = agent
     self.name = 'test_generalization'
     self.action_selector = State_goal_max_action_selector(agent)
     self.player = Player(agent)
     self.rewards = agent.ep_env_steps * agent.wrapper.rNotTerm * np.ones(2)
     self.stat_steps = np.zeros(2)
Ejemplo n.º 26
0
    def _parse_players(line: str, trump: TrumpType) -> List[Player]:
        """
        Helper for parse_file.
        Example: line is such -
            [Deal "E:AK872.KQJT.K.Q94 QT95.85.AQJ2.AK7 4.A962.96.J86532 J63.743.T87543.T"]
            And the result is list of Player object. First is Player(PositionEnum.E, Hand)
            such that Hand is list contain A, K, 8, 7, 2 faces of suit ♠, ect.
        :param line: line from PBN file, which starts with "[Deal "
        :return: list of 4 Player objects, sorted by (N, E, S, W)
        """
        player_str, all_hands_str = line.split(':')
        next_position = POSITIONS[PLAYERS_DICT[player_str]]

        players = [None, None, None, None]
        players_str = all_hands_str.split(
            ' ')  # spaces separate every two players
        for p in players_str:
            curr_position = next_position
            cards_str = p.split('.')  # dots separate every two suits
            cards = []
            for i, suit in enumerate(cards_str):
                for face in suit:
                    cards.append(
                        Card(face=face,
                             suit=SuitType(SUITS[i]).name,
                             trump=trump))
                    next_position = PLAYERS_CYCLE[curr_position]
            players[curr_position.value - 1] = Player(curr_position,
                                                      Hand(cards))

        return players
Ejemplo n.º 27
0
def get_player_information(MAX_PLAYERS):
    """get player information"""
    import random
    from players import Player, SimpleAI, SmartAI

    # create players list
    players = []
    # how many human players?
    print("\nHow many human players [1-4]:")
    no_of_players = get_int_input(1, MAX_PLAYERS)
    # for each player, get name
    for i in range(no_of_players):
        print("Please enter the name of player " + str(i + 1) + ":")
        players.append(Player(get_string_input()))

    ai_names = ['Angela', 'Bart', 'Charly', 'Dorothy']

    # how many AI players? ensure there are at least 2 players
    min = 1 if (len(players) == 1) else 0
    max = MAX_PLAYERS - no_of_players
    print(f"\nHow many ai players [{min:d}-{max:d}]:")
    no_of_players = get_int_input(min, max)
    # for each ai player, get name
    for name in ai_names[:no_of_players]:
        if random.choice([True, False]):
            players.append(SimpleAI(name))
        else:
            players.append(SmartAI("Smart " + name))

    return players
Ejemplo n.º 28
0
    def __init__(self, game_context, levelid):
        map_def = levels[levelid]
        self.name = map_def['name']
        self.elements = pygame.sprite.Group()
        size = map_def['size']
        self.tiles = list([None for r in range(size[1])]
                          for c in range(size[0]))
        self.background = Background((0, 0, 0))
        self.tilesize = map_def['tilesize']
        self.tilemap = map_def['tilemap']
        self.mobs = []
        self.spawns = {}
        self.clock = game_context.clock
        self.resolution = game_context.resolution
        self.game_context = game_context
        self.player_pos = map_def['player_pos']
        self.players = {}
        player_initdata = dict()
        player_initdata['centerx'] = self.player_pos[0]
        player_initdata['centery'] = self.player_pos[1]
        self.players["player_one"] = Player(AlloyShip,
                                            self.game_context,
                                            initdata=player_initdata)

        spawns = map_def.get('spawns', [])
        for spawn_group in spawns:
            mob_class_name, definitions = spawn_group.popitem()
            self.add_spawns(mob_class_name, definitions)
Ejemplo n.º 29
0
 def test_player_should_use_starting_strategy(self):
     deck = Deck()
     player = Player(starting_strategy=lambda: True)
     # with this strategy, the player choose always start
     # no matter the card he's being offered
     for card in deck:
         assert player.chooses_to_start(card)
Ejemplo n.º 30
0
 def test_player_should_give_card_to_trick_when_playing(self):
     player = Player()
     card = Card("C", "S")
     trick = Trick()
     player.add_card_to_hand(card)
     player.play(trick, 0)
     assert len(trick) == 1