예제 #1
0
def test_play_roll_dice_3(monkeypatch):
    # Given
    board = Board.create(players=[1, 3])
    state = GameState.create(board)
    dice = Dice()
    monkeypatch.setattr(dice, "roll", lambda: 3)
    game = GameEngine(board, dice)

    # When
    new_state = game.play(GameMove.roll_dice(player=1))

    # Then
    assert new_state == game.get_state()
    assert new_state.number == 1
    assert new_state.dice == 3
    assert new_state.valid_actions == [GameMove.roll_dice(player=3)]

    # And When
    new_state = game.play(GameMove.roll_dice(player=3))

    # Then
    assert new_state == game.get_state()
    assert new_state.number == 2
    assert new_state.dice == 3
    assert new_state.valid_actions == [GameMove.roll_dice(player=1)]
예제 #2
0
    def _fitnessEvaluations(self, pacmen, ghosts):
        totalGames = max(len(pacmen), len(ghosts))
        pacManNumber = 0
        ghostNumber = 0
        for evaluation in range(totalGames):
            pacMan = None
            ghost = None
            if pacManNumber > len(pacmen) - 1:
                pacManNumber = 0
            if ghostNumber > len(ghosts) - 1:
                ghostNumber = 0
            pacMan = pacmen[pacManNumber]
            ghost = ghosts[ghostNumber]

            engine = GameEngine(self.configDict, pacMan.parseTree,
                                ghost.parseTree)
            engine.runGame()
            pacMan, ghost = self._evaluateFitness(engine, pacMan, ghost)
            pacmen[pacManNumber] = pacMan
            ghosts[ghostNumber] = ghost

            pacManNumber += 1
            ghostNumber += 1

        return pacmen, ghosts
예제 #3
0
파일: main.py 프로젝트: revan7/tictactoe-ai
def main():
    board = Board()
    engine = GameEngine(board)
    cross_player = AIPlayer(1, "dude", engine)
    noughts_player = HumanPlayer(-1, "Rand", engine)
    view = BoardView(board)
    done = False
    view.update()
    while not done:
        try:
            cross_player.make_move()
            view.update()
            if engine.game_ended():
                view.reset()
                continue
            noughts_player.make_move()
            view.update()
            if engine.game_ended():
                view.reset()
                continue
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    done = True
        except Exception:
            traceback.print_exc()
예제 #4
0
def test_do_not_move_piece_to_end_on_bigger_dice(monkeypatch):
    # Given we have started the game and a piece is in the safe zone
    board = Board.create(players=[0, 2], pieces_per_player=1)
    state = GameState.create(board)
    dice = Dice()
    monkeypatch.setattr(dice, "roll", lambda: 5)
    game = GameEngine(board, dice)

    state.board.pieces[0].progress = board.end_progress - 3

    # When we roll the dice with 5 which is bigger then we need to
    # get to the goal
    new_state = game.play(GameMove.roll_dice(player=0))

    # Then the piece should not go to the goal and it should be the
    # next player turn
    assert new_state == game.get_state()
    assert new_state.number == 1
    assert new_state.dice == 5
    assert new_state.valid_actions == [
        GameMove.roll_dice(player=2),
    ]
    assert new_state.board.pieces == [
        Piece(number=0, player=0, progress=board.end_progress - 3),
        Piece(number=0, player=2, progress=0),
    ]
    assert new_state.winners == []
예제 #5
0
def test_do_move_and_knock_out(monkeypatch):
    dice1 = Dice()
    monkeypatch.setattr(dice1, "roll", lambda: 1)
    dice5 = Dice()
    monkeypatch.setattr(dice5, "roll", lambda: 5)
    dice6 = Dice()
    monkeypatch.setattr(dice6, "roll", lambda: 6)

    b = Board.create(players=[0, 1], pieces_per_player=1)
    g = GameEngine(b)
    assert GameMove.roll_dice(0) in g.state.valid_actions

    g.dice = dice1
    s = g.play(GameMove.roll_dice(0))
    assert GameMove.roll_dice(1) in s.valid_actions

    g.dice = dice6
    s = g.play(GameMove.roll_dice(1))
    s = g.play(GameMove.piece_out(1, 0))
    assert s.board.pieces == [Piece(0, 0, 0), Piece(0, 1, 1)]
    assert GameMove.roll_dice(1) in s.valid_actions

    s = g.play(GameMove.roll_dice(1))
    s = g.play(GameMove.move_piece(1, 0, 6))
    assert s.board.pieces == [Piece(0, 0, 0), Piece(0, 1, 7)]
    assert GameMove.roll_dice(1) in s.valid_actions

    s = g.play(GameMove.roll_dice(1))
    s = g.play(GameMove.move_piece(1, 0, 6))
    assert s.board.pieces == [Piece(0, 0, 0), Piece(0, 1, 13)]
    assert GameMove.roll_dice(1) in s.valid_actions

    s = g.play(GameMove.roll_dice(1))
    s = g.play(GameMove.move_piece(1, 0, 6))
    assert s.board.pieces == [Piece(0, 0, 0), Piece(0, 1, 19)]
    assert GameMove.roll_dice(1) in s.valid_actions

    g.dice = dice5
    s = g.play(GameMove.roll_dice(1))
    s = g.play(GameMove.move_piece(1, 0, 5))
    assert s.board.pieces == [Piece(0, 0, 0), Piece(0, 1, 24)]
    assert GameMove.roll_dice(0) in s.valid_actions

    g.dice = dice6
    s = g.play(GameMove.roll_dice(0))
    assert GameMove.piece_out(0, 0) in s.valid_actions
    s = g.play(GameMove.piece_out(0, 0))
    assert s.board.pieces == [Piece(0, 0, 1), Piece(0, 1, 24)]

    g.dice = dice1
    s = g.play(GameMove.roll_dice(0))
    s = g.play(GameMove.move_piece(0, 0, 1))
    assert s.board.pieces == [Piece(0, 0, 2), Piece(0, 1, 24)]

    g.dice = dice6
    s = g.play(GameMove.roll_dice(1))
    assert GameMove.move_piece(1, 0, 6) in s.valid_actions
    s = g.play(GameMove.move_piece(1, 0, 6))
    # player 1 hits player 0 and sends her home
    assert s.board.pieces == [Piece(0, 0, 0), Piece(0, 1, 30)]
예제 #6
0
def main(argv):
    engine = GameEngine()
    engine.check_file_integrity("../data/test_init.json")

    engine.initialize_from_file("../data/test_init.json")
    result = engine.compute()

    print(result)
예제 #7
0
def application(environ, start_response):

    try:
        if environ['REQUEST_METHOD'] == 'POST':
            request_body_size = int(environ.get('CONTENT_LENGTH', '0'))
            request_body = environ['wsgi.input'].read(request_body_size)
            data = json.loads(request_body.decode())

            WORLDS = {}

            world = data['world']
            if world not in WORLDS:
                with open('public/' + world + '/OBJECTS.json') as f:
                    objects = json.load(f)
                with open('public/' + world + '/ROOMS.json') as f:
                    rooms = json.load(f)
                WORLDS['world'] = [objects, rooms]

            world = WORLDS['world']
            game = GameEngine(world[0], world[1])

            game.set_state(data['state'])

            cmd = game.decode_button_command(data['user_command'])
            prs = game.process_command(cmd)

            audio_prs = game.prompts_only(prs)
            text_prs = game.text_only(prs)

            ndata = {
                'text': text_prs,
                'audio': audio_prs,
                'state': game.get_state()
            }

            start_response('200 OK', [('Content-Type', 'application/json')])
            return [json.dumps(ndata).encode()]

        else:
            # If we are running alongside a web server then the server will handle static files.
            # This is for the stand-alone case (like running on the Farmer Says)
            fn = environ['PATH_INFO']
            if fn == '/':
                fn = '/index.html'
            print('*', fn, '*')
            with open('public' + fn, 'rb') as f:
                data = f.read()
            if fn.endswith('.json'):
                start_response('200 OK', [('Content-Type', 'application/json')])
            else:
                start_response('200 OK', [('Content-Type', 'text/html')])
            return [data]
    except Exception:
        with open('ex.txt', 'w') as f:
            f.write(traceback.format_exc())
        raise
예제 #8
0
def test_initial_gate_state(monkeypatch):
    # Given
    board = Board.create(players=[1, 3])
    state = GameState.create(board)

    # When
    game = GameEngine(board)

    # Then
    assert game.state == state
예제 #9
0
def test_play_to_leaf_with_sims():
    d = Deal(seed=0)
    disp = Displayer()
    dec = Decisions()
    sim = Simulator()
    e = GameEngine(disp, dec, sim)

    sims = sim.load_sims(0)
    d = e.play_to_leaf(d, sims, random=False)
    assert_equal(d.full_history[0][1], d.trick_tally)
예제 #10
0
    def reinit(self):
        game = Application.GAMES[self._game_number]
        with open('public/' + game + '/ROOMS.json') as f:
            rooms = json.load(f)

        with open('public/' + game + '/OBJECTS.json') as f:
            objects = json.load(f)

        self._engine = GameEngine(objects, rooms)

        self._hardware.set_audio_path('public/' + game + '/audio/')
예제 #11
0
def main():
    """Main function to bootstrap the game."""
    board_generator = BoardGenerator()
    config_parser = JSONConfigParser()
    config_loader = ConfigLoader(CONFIG_FILE_PATH, config_parser)
    console_input = ConsoleInput()
    console_output = ConsoleOutput()
    game_engine = GameEngine(board_generator)
    validator = StrToIntValidator()
    menu = Menu(config_loader, game_engine, console_input, console_output,
                validator)
    menu.run_main_menu()
예제 #12
0
    def __init__(self, size):
        """
		Draw game's grid/universe

		Arguments:
			size {int tuple} -- size of grid to draw (x, y)
		"""
        # init self state as randomized binary value based on given tuple (size)
        self.state = RNG.integers(2, size=size)

        # init self access to GameEngine class
        self.gameEngine = GameEngine(self)
예제 #13
0
def test_do_move_take_out_of_home_and_knock_out(monkeypatch):
    dice4 = Dice()
    monkeypatch.setattr(dice4, "roll", lambda: 4)
    dice6 = Dice()
    monkeypatch.setattr(dice6, "roll", lambda: 6)

    b = Board.create(players=[0, 1], pieces_per_player=1)
    g = GameEngine(b)
    assert GameMove.roll_dice(0) in g.state.valid_actions

    g.dice = dice4
    s = g.play(GameMove.roll_dice(0))
    assert GameMove.roll_dice(1) in s.valid_actions

    g.dice = dice6
    s = g.play(GameMove.roll_dice(1))
    s = g.play(GameMove.piece_out(1, 0))
    assert s.board.pieces == [Piece(0, 0, 0), Piece(0, 1, 1)]
    assert s.valid_actions == [GameMove.roll_dice(1)]

    s = g.play(GameMove.roll_dice(1))
    s = g.play(GameMove.move_piece(1, 0, 6))
    assert s.board.pieces == [Piece(0, 0, 0), Piece(0, 1, 7)]
    assert s.valid_actions == [GameMove.roll_dice(1)]

    s = g.play(GameMove.roll_dice(1))
    s = g.play(GameMove.move_piece(1, 0, 6))
    assert s.board.pieces == [Piece(0, 0, 0), Piece(0, 1, 13)]
    assert s.valid_actions == [GameMove.roll_dice(1)]

    s = g.play(GameMove.roll_dice(1))
    s = g.play(GameMove.move_piece(1, 0, 6))
    assert s.board.pieces == [Piece(0, 0, 0), Piece(0, 1, 19)]
    assert s.valid_actions == [GameMove.roll_dice(1)]

    s = g.play(GameMove.roll_dice(1))
    s = g.play(GameMove.move_piece(1, 0, 6))
    assert s.board.pieces == [Piece(0, 0, 0), Piece(0, 1, 25)]
    assert s.valid_actions == [GameMove.roll_dice(1)]

    g.dice = dice4
    s = g.play(GameMove.roll_dice(1))
    s = g.play(GameMove.move_piece(1, 0, 4))
    assert s.board.pieces == [Piece(0, 0, 0), Piece(0, 1, 29)]
    assert s.valid_actions == [GameMove.roll_dice(0)]

    g.dice = dice6
    s = g.play(GameMove.roll_dice(0))
    assert GameMove.piece_out(0, 0) in s.valid_actions
    s = g.play(GameMove.piece_out(0, 0))

    assert s.board.pieces == [Piece(0, 0, 1), Piece(0, 1, 0)]
예제 #14
0
def test_play_invalid_action_on_initial_state(monkeypatch):
    # Given
    board = Board.create(players=[1, 3])
    state = GameState.create(board)
    game = GameEngine(board)

    # When we try to play an invalid action PieceOut
    with pytest.raises(Exception):
        game.play(GameMove.piece_out(1, 1))

    # When we try to play valid action for an invalid Player
    with pytest.raises(Exception):
        game.play(GameMove.roll_dice(player=3))
예제 #15
0
def test_play_to_all_leaves():
    d = Deal(seed=0)
    d.make_lead()
    # print(d.original_hands)
    disp = Displayer()
    dec = Decisions()
    sim = Simulator()
    e = GameEngine(disp, dec, sim)
    e.play_to_all_leaves(d)
    assert_equal(d.trick_no, 5)
    assert_equal(d.card_no, 17)
    assert_equal(d.current_trick, [])
    # we save this number from a previous run. Good to check we always traverse the whole tree
    assert_equal(d.leaf_nodes, 832)
예제 #16
0
    def _initializePopulation(self):
        newPacMen = []
        numberOfPacMen = self.configDict["pacmanPopulationSize"]
        if self.totalEvals < numberOfPacMen:
            numberOfPacMen = self.totalEvals
        newGhosts = []
        numberOfGhosts = self.configDict["ghostPopulationSize"]
        if self.totalEvals < numberOfGhosts:
            numberOfGhosts = self.totalEvals

        totalGames = max(numberOfPacMen, numberOfGhosts)
        for evaluation in range(totalGames):
            pacMan = None
            ghost = None
            # Random number passed to _generateSolution implements ramped half and half.
            if numberOfPacMen > 0:
                pacMan = self._generateSolution("pac-man",
                                                random.randint(0, 1))
                numberOfPacMen -= 1
            if numberOfGhosts > 0:
                ghost = self._generateSolution("ghost", random.randint(0, 1))
                numberOfGhosts -= 1

            reusedPacManInd = -1
            reusedGhostInd = -1
            if not pacMan:
                reusedPacManInd = random.randint(0, len(newPacMen) - 1)
                pacMan = newPacMen[reusedPacManInd]
            elif not ghost:
                reusedGhostInd = random.randint(0, len(newGhosts) - 1)
                ghost = newGhosts[reusedGhostInd]

            engine = GameEngine(self.configDict, pacMan.parseTree,
                                ghost.parseTree)
            engine.runGame()
            pacMan, ghost = self._evaluateFitness(engine, pacMan, ghost)\

            if reusedPacManInd != -1:
                newPacMen[reusedPacManInd] = pacMan
            else:
                newPacMen.append(pacMan)

            if reusedGhostInd != -1:
                newGhosts[reusedGhostInd] = ghost
            else:
                newGhosts.append(ghost)

        self.pacmanPopulation = newPacMen
        self.ghostPopulation = newGhosts
예제 #17
0
def test_roll(monkeypatch, client):
    # Given 4 players had joined in the previous tests and the game had starte

    # When we try to play with the correct user token
    rv = client.get("/play/roll", headers={"4oBe4e-user-token": player1_token})
    game_state = json.loads(rv.data)

    board = Board.create(players=[0, 1, 2, 3])
    dice = Dice()
    monkeypatch.setattr(dice, "roll", lambda: game_state["dice"])
    game = GameEngine(board, dice)
    game.play(GameMove.roll_dice(player=0))

    # Then we want the same state as the default for 4 players
    assert game_state == dataclasses.asdict(game.get_state())
예제 #18
0
def game_loop():
    engine = GameEngine()
    running = True

    while running:
        clock.tick(40)

        if pygame.event.get(pygame.QUIT):
            running = False
            return
        engine.scene.handle_events(pygame.event.get())
        engine.scene.update()
        engine.scene.render(gameDisplay)
        pygame.display.update(engine.scene.rects_to_update)
        engine.scene.rects_to_update = []
    """
예제 #19
0
def test_play_to_leaf():
    deal = {
        'N': set(['C14', 'C13', 'C12', 'C11']),
        'E': set(['S14', 'S13', 'H12', 'H11']),
        'S': set(['D14', 'D13', 'H14', 'H13']),
        'W': set(['D12', 'D11', 'S12', 'S11'])
    }
    d = Deal(deal=deal)
    disp = Displayer()
    dec = Decisions()
    sim = Simulator()
    e = GameEngine(disp, dec, sim)
    e.play_to_leaf(d)
    assert_equal(d.trick_no, 5)
    assert_equal(d.card_no, 17)
    assert_equal(d.current_trick, [])
    assert_equal(d.leaf_nodes, 1)
예제 #20
0
def test_find_all_layouts_and_run_sims():
    deal = {
        'N': set(['C14', 'C13', 'C12', 'C11']),
        'E': set(['S14', 'S13', 'H12', 'H11']),
        'S': set(['D14', 'D13', 'H14', 'H13']),
        'W': set(['D12', 'D11', 'S12', 'S11'])
    }
    d = Deal(deal=deal)
    sim = Simulator()
    dec = Decisions()
    disp = Displayer()

    e = GameEngine(disp, dec, sim)
    d.make_lead('D12')
    layouts = sim.find_layouts(d)
    # This should be the case because west has played a card already and north/south haven't
    assert (len(layouts[2]) > len(layouts[0]))
예제 #21
0
def test_generate_possible_layouts():
    d = Deal(seed=0)
    disp = Displayer()
    dec = Decisions()
    sim = Simulator()
    e = GameEngine(disp, dec, sim)

    layouts = sim.generate_layouts('NS',
                                   set(['D12', 'D11', 'S12', 'S11']),
                                   set(['C14', 'C13', 'C12', 'C11']),
                                   d.all_cards,
                                   lead=set([]))

    assert_equal(len(layouts), scipy.special.comb(8, 4))
    my_layout = {
        'N': set(['C14', 'C13', 'C12', 'C11']),
        'E': set(['S14', 'S13', 'H12', 'H11']),
        'S': set(['D12', 'D11', 'S12', 'S11']),
        'W': set(['D14', 'D13', 'H14', 'H13'])
    }
예제 #22
0
def test_play_roll_dice_6(monkeypatch):
    # Given
    board = Board.create(players=[1, 3])
    state = GameState.create(board)
    dice = Dice()
    monkeypatch.setattr(dice, "roll", lambda: 6)
    game = GameEngine(board, dice)

    # When
    new_state = game.play(GameMove.roll_dice(player=1))

    # Then
    # assert new_state == game.get_state()
    assert new_state.number == 1
    assert new_state.dice == 6
    assert new_state.valid_actions == [
        GameMove.piece_out(player=1, piece=0, dice=6),
        GameMove.piece_out(player=1, piece=1, dice=6),
        GameMove.piece_out(player=1, piece=2, dice=6),
        GameMove.piece_out(player=1, piece=3, dice=6),
    ]
예제 #23
0
def join(player: str):
    global engine  # TODO Where shall we keep the curren running GameEngine/s ?
    if player in player_name_token:
        token = player_name_token[player]
        num = player_token_number[token]
        return jsonify({"player_token": token, "player_num": num})
    if len(player_token_name) == 4:
        players: Dict[str, int] = dict(
            (name, player_token_number[token])
            for name, token in player_name_token.items())
        raise ValueError("Game is full. Players are ", players)
    player_uuid: str = str(uuid.uuid4())
    player_token_name[player_uuid] = player
    player_number: int = len(player_token_number)
    player_name_token[player] = player_uuid
    player_token_number[player_uuid] = player_number
    if len(player_token_name) == 4:
        board = Board.create(list(player_token_number.values()))
        engine = GameEngine(board)
        __state_to_json(engine.state)
    return jsonify({"player_token": player_uuid, "player_num": player_number})
예제 #24
0
    def __init__(self, game, use_audio=True):

        if use_audio:
            print('Loading hardware ...')
            from farmer_says import FarmerSays
            print('... done')
            self._hardware = FarmerSays()
            self._hardware.start_audio_thread()
        else:
            self._hardware = None

        with open('public/' + game + '/ROOMS.json') as f:
            rooms = json.load(f)

        with open('public/' + game + '/OBJECTS.json') as f:
            objects = json.load(f)

        self._engine = GameEngine(objects, rooms)

        if self._hardware:
            self._hardware.set_audio_path('public/' + game + '/audio/')
예제 #25
0
 def __init__(self):
     self.process_stack = []
     self.game_engine = GameEngine(self)
     self.state_continuous = True
     self.current_state = None
     self.ending_message = ''
예제 #26
0
def test_play_until_the_end_two_players_once_piece(monkeypatch):
    # Given we have started the game
    board = Board.create(players=[0, 2], pieces_per_player=1)
    state = GameState.create(board)
    dice = Dice()
    monkeypatch.setattr(dice, "roll", lambda: 6)
    game = GameEngine(board, dice)

    # When we roll the dice
    new_state = game.play(GameMove.roll_dice(player=0))

    # Then the state should be as expected
    assert new_state == game.get_state()
    assert new_state.number == 1
    assert new_state.dice == 6
    assert new_state.valid_actions == [
        GameMove.piece_out(player=0, piece=0, dice=6),
    ]

    # And When we play getting out with the first peice
    new_state = game.play(GameMove.piece_out(player=0, piece=0, dice=6))
    # Then the first piece should be out
    assert new_state.current_player == 0
    assert new_state.number == 2
    assert new_state.dice == 6
    assert new_state.board.pieces == [
        Piece(number=0, player=0, progress=1),
        Piece(number=0, player=2, progress=0),
    ]
    assert new_state.valid_actions == [GameMove.roll_dice(player=0)]

    # And When we row the dice again with 6
    new_state = game.play(GameMove.roll_dice(player=0))
    # Then we should should be able to move the piece forward
    assert new_state.number == 3
    assert new_state.dice == 6
    assert new_state.valid_actions == [GameMove.move_piece(player=0, piece=0, dice=6)]

    # And When we move the piece
    new_state = game.play(GameMove.move_piece(player=0, piece=0, dice=6))
    # Then it should go forward and we should be able to roll the dice again
    assert new_state.number == 4
    assert new_state.winners == []
    assert new_state.board.pieces == [
        Piece(number=0, player=0, progress=7),
        Piece(number=0, player=2, progress=0),
    ]
    assert new_state.valid_actions == [GameMove.roll_dice(player=0)]

    # And When we roll the dice again with 6
    new_state = game.play(GameMove.roll_dice(player=0))
    # Then we should be able to move the piece forward
    assert new_state.dice == 6
    assert new_state.number == 5
    assert new_state.valid_actions == [GameMove.move_piece(player=0, piece=0, dice=6)]

    # And When we move the piece
    new_state = game.play(GameMove.move_piece(player=0, piece=0, dice=6))
    # Then the piece should go forward and we should be able to roll the dice again
    assert new_state.number == 6
    assert new_state.board.pieces == [
        Piece(number=0, player=0, progress=13),
        Piece(number=0, player=2, progress=0),
    ]
    assert new_state.winners == []
    assert new_state.valid_actions == [GameMove.roll_dice(player=0)]

    # And When we position the piece toward the end of the board
    new_state.board.pieces[0].progress = board.end_progress - 6

    # And When we roll the dice again with 6
    new_state = game.play(GameMove.roll_dice(player=0))
    # Then we should be able to move the piece forward into the safe zone and to the goal
    assert new_state.dice == 6
    assert new_state.number == 7
    assert new_state.valid_actions == [GameMove.move_piece(player=0, piece=0, dice=6)]

    # And When we move the piece
    new_state = game.play(GameMove.move_piece(player=0, piece=0, dice=6))
    # Then the piece should go forward and we should be able to roll the dice again
    assert new_state.number == 8
    assert new_state.board.pieces == [
        Piece(number=0, player=0, progress=board.end_progress),
        Piece(number=0, player=2, progress=0),
    ]
    assert new_state.winners == [0]
    assert new_state.valid_actions == []
import math

from display import YELLOW, RED
from engine import GameEngine
from agents.human_agent import HumanAgent
from agents.minimax_agent import MiniMaxAgent
from agents.random_agent import RandomAgent
from player1 import Player1
from player2 import Player2

if __name__ == "__main__":

    engine = GameEngine(YELLOW, RED)
    engine.init_display()

    # TODO: Separate AgentGlobalParams (HyperParams?) and AgentTurnParams

    human_agent = HumanAgent(params={'display': engine.display})
    random_agent = RandomAgent()
    minimax_agent = MiniMaxAgent(params={
        'depth': 5,
        'alpha': -math.inf,
        'beta': math.inf,
        'maximizingPlayer': True
    })

    human_player1 = Player1(human_agent, "Human 1")
    human_player2 = Player2(human_agent, "Human 2")
    minimax_player1 = Player1(minimax_agent, "MiniMax 1")
    minimax_player2 = Player2(minimax_agent, "MiniMax 2")
    random_player1 = Player1(random_agent, "Random 1")
예제 #28
0
 def setUp(self):
     pygame.init()
     self.engine = GameEngine()
예제 #29
0
 def createHeadless(self):
     """Create a headless game."""
     gamemanager = self.createGameManager()
     engine = GameEngine()
     engine.updateables.append(gamemanager)
     return (engine, gamemanager)
예제 #30
0
def test_move_blocked(monkeypatch):
    dice1 = Dice()
    monkeypatch.setattr(dice1, "roll", lambda: 1)
    dice5 = Dice()
    monkeypatch.setattr(dice5, "roll", lambda: 5)
    dice6 = Dice()
    monkeypatch.setattr(dice6, "roll", lambda: 6)

    b = Board.create(players=[0, 1], pieces_per_player=2)
    g = GameEngine(b)
    assert GameMove.roll_dice(0) in g.state.valid_actions

    g.dice = dice5
    s = g.play(GameMove.roll_dice(0))
    assert GameMove.roll_dice(1) in s.valid_actions

    g.dice = dice6
    s = g.play(GameMove.roll_dice(1))
    s = g.play(GameMove.piece_out(1, 0))
    assert s.board.pieces == [Piece(0, 0), Piece(1, 0), Piece(0, 1, 1), Piece(1, 1)]
    assert GameMove.roll_dice(1) in s.valid_actions

    s = g.play(GameMove.roll_dice(1))
    s = g.play(GameMove.piece_out(1, 1))
    assert s.board.pieces == [Piece(0, 0), Piece(1, 0), Piece(0, 1, 1), Piece(1, 1, 1)]
    assert GameMove.roll_dice(1) in s.valid_actions

    s = g.play(GameMove.roll_dice(1))
    s = g.play(GameMove.move_piece(1, 0, 6))
    s = g.play(GameMove.roll_dice(1))
    s = g.play(GameMove.move_piece(1, 1, 6))
    assert s.board.pieces == [Piece(0, 0), Piece(1, 0), Piece(0, 1, 7), Piece(1, 1, 7)]
    assert GameMove.roll_dice(1) in s.valid_actions

    s = g.play(GameMove.roll_dice(1))
    s = g.play(GameMove.move_piece(1, 0, 6))
    s = g.play(GameMove.roll_dice(1))
    s = g.play(GameMove.move_piece(1, 1, 6))
    assert s.board.pieces == [
        Piece(0, 0),
        Piece(1, 0),
        Piece(0, 1, 13),
        Piece(1, 1, 13),
    ]
    assert GameMove.roll_dice(1) in s.valid_actions

    s = g.play(GameMove.roll_dice(1))
    s = g.play(GameMove.move_piece(1, 0, 6))
    s = g.play(GameMove.roll_dice(1))
    s = g.play(GameMove.move_piece(1, 1, 6))
    assert s.board.pieces == [
        Piece(0, 0),
        Piece(1, 0),
        Piece(0, 1, 19),
        Piece(1, 1, 19),
    ]
    assert GameMove.roll_dice(1) in s.valid_actions

    s = g.play(GameMove.roll_dice(1))
    s = g.play(GameMove.move_piece(1, 0, 6))
    s = g.play(GameMove.roll_dice(1))
    s = g.play(GameMove.move_piece(1, 1, 6))
    assert s.board.pieces == [
        Piece(0, 0),
        Piece(1, 0),
        Piece(0, 1, 25),
        Piece(1, 1, 25),
    ]
    assert GameMove.roll_dice(1) in s.valid_actions

    g.dice = dice5
    s = g.play(GameMove.roll_dice(1))
    s = g.play(GameMove.move_piece(1, 0, 5))
    assert s.board.pieces == [
        Piece(0, 0),
        Piece(1, 0),
        Piece(0, 1, 30),
        Piece(1, 1, 25),
    ]
    assert s.valid_actions == [GameMove.roll_dice(0)]

    s = g.play(GameMove.roll_dice(0))

    # i.e. player 0 can't move
    assert s.valid_actions == [GameMove.roll_dice(1)]

    s = g.play(GameMove.roll_dice(1))
    s = g.play(GameMove.move_piece(1, 1, 5))
    assert s.board.pieces == [
        Piece(0, 0),
        Piece(1, 0),
        Piece(0, 1, 30),
        Piece(1, 1, 30),
    ]
    assert s.valid_actions == [GameMove.roll_dice(0)]

    g.dice = dice6
    s = g.play(GameMove.roll_dice(0))
    s = g.play(GameMove.piece_out(0, 0))
    assert s.board.pieces == [
        Piece(0, 0, 1),
        Piece(1, 0),
        Piece(0, 1, 30),
        Piece(1, 1, 30),
    ]
    assert s.valid_actions == [GameMove.roll_dice(0)]

    g.dice = dice1
    s = g.play(GameMove.roll_dice(0))
    # i.e. player 0 can't move: piece 1 is not out, and piece 0 is blocked
    assert s.valid_actions == [GameMove.roll_dice(1)]