Exemplo n.º 1
0
def get_reward_board(board):
    m = len(board)
    n = len(board[0])
    original_gameboard = GameBoard(board=board)
    reward_board = [[-1 for j in range(n)] for i in range(m)]
    avail_choices = original_gameboard.get_available_choices()
    for (x, y) in avail_choices:
        new_gameboard = GameBoard(board=board)
        reward = new_gameboard.proceed_next_state(x, y)
        reward_board[x][y] = reward
    return reward_board
Exemplo n.º 2
0
def main():
    game_board = GameBoard()
    graphics = Graphics((800, 800), game_board)

    while True:
        play_game(game_board, graphics)

        if players_are_bored(graphics):
            break

        game_board = GameBoard()
        graphics.game_board = game_board
Exemplo n.º 3
0
    def minimax(self, board, isMaximizer, lastMove) -> (int, int):

        gBoard = GameBoard(board)
        #gBoard.display()
        if not self.getResult(gBoard) == 0:
            if isMaximizer:
                return (self.getResult(gBoard), lastMove)
            return (-self.getResult(gBoard), lastMove)
        move = -1
        score = -2
        #boardMatrix = board.getBoard()
        for i in range(9):
            if board[i // 3][i % 3] == " ":
                boardWithNewMove = copy.deepcopy(board)
                if isMaximizer:
                    #print("maximizer")
                    boardWithNewMove[i // 3][i % 3] = "X"
                else:
                    #print("minimizer")
                    boardWithNewMove[i // 3][i % 3] = "O"

                scoreMove = self.minimax(boardWithNewMove, not isMaximizer, i)
                scoreForTheMove = -scoreMove[0]
                #print("tuple",scoreMove,"maxScore",score,"isMaximizer",isMaximizer)
                if scoreForTheMove > score:

                    score = scoreForTheMove
                    move = i

        if move == -1:
            return (0, -1)
        #print("returning",score,move)
        return (score, move)
Exemplo n.º 4
0
    def update(self):
        # Main event loop
        for self.event in pygame.event.get():
            if self.event.type == pygame.KEYDOWN:
                self.key_check()

        delay = 0.27 - self.level * 0.005
        if self.gameboard.slow_time_on:
            delay *= 2
            if time.perf_counter() - self.slow_activation_time > 6:
                self.gameboard.slow_time_on = False

        if self.gameboard.swap_shape:
            self.shape = self.next_shape
            self.next_shape = Shape()
            self.gameboard.swap_shape = False

        if time.perf_counter() - self.last_time > delay:
            self.last_time = time.perf_counter()
            self.shape.falling()

        if self.shape.active == False:
            self.gameboard.clear_full_rows()
            self.shape = self.next_shape
            self.next_shape = Shape()
        if self.gameboard.check_loss():
            new_score = self.gameboard.score / 2
            num_lines = self.gameboard.num_lines
            self.gameboard = GameBoard(WHITE, self.shape.block_list[0].size)
            self.gameboard.score = new_score
            self.gameboard.num_lines = num_lines
            self.shape = Shape()
            self.next_shape = Shape()
        if time.perf_counter() - self.start_time > 120:
            self.done_level = True
Exemplo n.º 5
0
def default_policy(node):

    # Get the state of the game
    current_state = node.state
    #print(current_state.current_board)

    #############
    ## Then add the inferencing score
    #big_score = big_inferencer.inference(current_state.current_board)
    # small_score = small_inferencer.inference(current_state.current_board)
    # return big_score + small_score
    #############

    ############
    simulation_board = GameBoard(current_state.current_board, simulation=True)

    while current_state.is_terminal(rollout=True) == False:

        # Pick one random action to play and get next state
        current_state = current_state.get_next_state_with_random_choice(
            simulation_board)

    final_state_reward = current_state.compute_reward(simulation_board)

    return final_state_reward  #+ big_score
Exemplo n.º 6
0
def main():
    board = GameBoard()
    board.set_up()
    while True:
        board.print()
        cell_reference = input(
            "Enter cell to fire at (e.g. A1, B1, ...) or q to quit: ")
        if cell_reference == "q" or cell_reference == "Q":
            print("Bye!")
            return
        (row, column) = GameBoard.translate_cell_reference(cell_reference)
        if row == -1:
            print("'", cell_reference, "' is not a valid cell.", sep="")
            continue
        result = board.fire_missile(row, column)
        if result == FiringResult.HIT:
            print("Hit!")
        elif result == FiringResult.MISSED:
            print("Missed!")
        else:
            print("You've already been there!")
        if board.game_is_won:
            break
    board.print()
    print("Congratulations, you Won!")
Exemplo n.º 7
0
def double_player_game():
    board = GameBoard()
    print("Player 1: Please type in your name: ")
    player_name_1 = input()
    print("Player 2: Please type in your name: ")
    player_name_2 = input()

    player1 = Human('X', player_name_1)
    player2 = Human('O', player_name_2)

    current_player = player1
    other_player = player2
    winner = None
    game_over = False

    while not game_over:
        print(current_player.name, "Please select the column: [1-7]")
        print(board)
        move_allowed = False
        while not move_allowed:
            move = current_player.get_move(board, other_player)
            move_allowed = board.try_place_piece(move, current_player.sign)

        game_over, winner = board.is_game_over(board.board,
                                               current_player.sign,
                                               other_player.sign)
        current_player, other_player = other_player, current_player

    print(board)
    if winner:
        print("Player", other_player.name, "just won! Game over")
    else:
        print("Tie!")
Exemplo n.º 8
0
def findSquares(board):
    """Find complete squares of 3x3

    Return None if nothing is found
    Otherwise return a tuple.
        The first element is the number of squares found.
        The second is a copy of the board with each dead square marked."""

    newBoard = GameBoard()

    newBoard.copy(board)

    squareCount = 0

    # All setup, just mark those squares (if they exist)

    for j in range(newBoard.getHeight() - 3):
        for i in range(newBoard.getWidth() - 3):
            if newBoard.squareAt(i, j, 1):
                squareCount = squareCount + 1

    # Marked, check things

    if squareCount > 0:
        return (squareCount, newBoard)
    else:
        return None
Exemplo n.º 9
0
def glider_demo():
    a_game = GameBoard(8)
    a_game = add_glider(a_game)
    for i in range(50):
        print(a_game)
        sleep(1)
        a_game.progress()
Exemplo n.º 10
0
    def default_policy(self, node):

        current_state = node.state

        #         simulation_board = GameBoard(current_state.current_board, simulation = True)

        #         depth = 0
        #         while not current_state.is_terminal() and depth < self.MAX_ROLLOUT_DEPTH:

        #             # Pick one random action to play and get next state
        #             current_state = current_state.get_next_state_with_random_choice(simulation_board)
        #             depth += 1

        #         final_state_reward = simulation_board.score

        #         return final_state_reward

        simulation_board = GameBoard(current_state.current_board,
                                     simulation=True)
        total_score = 0
        for i in range(self.MAX_ROLLOUT_DEPTH):
            board = simulation_board.board
            available_choice = simulation_board.get_available_choices()
            choice = random.choice(available_choice)
            score = simulation_board.proceed_next_state(choice[0], choice[1])
            total_score += self.gamma**i * score
        return total_score
Exemplo n.º 11
0
def createGame(difficulty):
    global tileList, tileDictionary, gameBoard

    gameBoard = GameBoard()
    tileList = gameBoard.createBoard(difficulty)
    
    tileDictionary = copy.deepcopy(gameBoard.tileDictionary)
Exemplo n.º 12
0
 def test_birth(self):
     game = GameBoard(5)
     game.get_cell(1, 1).alive = True
     game.get_cell(1, 2).alive = True
     game.get_cell(1, 3).alive = True
     game.progress()
     self.assertTrue(game.get_cell(0, 2).alive)
Exemplo n.º 13
0
def single_player_game():
    board = GameBoard()
    print("Player 1: Please type in your name: ")
    player_name = input()
    player1 = Human('X', player_name)
    player2 = Computer('O', 6)
    print("Please select the column: [1-7]")

    current_player = player1
    other_player = player2

    winner = None
    game_over = False

    while not game_over:
        print(board)
        move_allowed = False
        while not move_allowed:
            start = time.time()  # Get the start time
            move = current_player.get_move(board, other_player)
            move_allowed = board.try_place_piece(move, current_player.sign)

        game_over, winner = board.is_game_over(board.board,
                                               current_player.sign,
                                               other_player.sign)
        end = time.time()  # Testing end time
        difference = end - start  # Get the time from start to end
        current_player, other_player = other_player, current_player
        print("Computing Time: ", difference)
    print(board)
    if winner:
        print("Computer Won! Game over")
    else:
        print("Tie!")
Exemplo n.º 14
0
def main():
    no_of_wins = 0
    no_of_ties = 0
    no_of_losses = 0
    print(" algorithm gaining experience")

    game_generator = Experiment(BOARD_DIMENSION)
    generalizer = Generalizer(19)  #19 because of 18 features + one constant w0

    critic = Critic(generalizer)
    for i in range(NUMBER_OF_EXaMPLES):
        board = game_generator.generate_board()

        performance_system = PerformanceMeasure(board, generalizer, critic,
                                                game_generator)
        result = performance_system.improve_system()

        examples, values = critic.fetch_training_examples()
        generalizer.set_training_examples(examples)
        generalizer.set_training_values(values)
        generalizer.LMS_weight_update_rule()

        if result == 100: no_of_wins += 1
        if result == -100: no_of_losses += 1
        if result == 0: no_of_ties += 1

    W = generalizer.get_weights()

    print(no_of_wins, no_of_ties, no_of_losses)
    """
        Playing against human...
    """

    while True:
        human_board = GameBoard([
            '-',
            '-',
            '-',
            '-',
            '-',
            '-',
            '-',
            '-',
            '-',
        ])

        vs_human = human_board.victor()
        while vs_human is None:
            x = int(input(" X coordinate: "))
            y = int(input(" Y coordinate: "))

            human_board._board[x * 3 + y] = 'X'

            computer_position = human_board.maximizer(W)
            human_board._board[computer_position] = 'O'

            print(human_board)

            vs_human = human_board.victor()
Exemplo n.º 15
0
    def __init__(self):
        pygame.init()

        self.screen = pygame.display.set_mode((800, 600))
        self.clock = pygame.time.Clock()
        self.font = pygame.font.Font(r"C:\Windows\Fonts\consola.ttf", 24)
        self.going = True
        self.gameboard = GameBoard()
Exemplo n.º 16
0
 def test_count_four_neighbours(self):
     game = GameBoard(5)
     game.get_cell(0, 0).alive = True
     game.get_cell(0, 1).alive = True
     game.get_cell(0, 2).alive = True
     game.get_cell(1, 0).alive = True
     count = game.count_living_neighbours(game.get_cell(1, 1))
     self.assertEqual(4, count)
Exemplo n.º 17
0
 def test_survive(self):
     game = GameBoard(5)
     test_cell = game.get_cell(2, 2)
     test_cell.alive = True
     game.get_cell(2, 1).alive = True
     game.get_cell(2, 3).alive = True
     game.progress()
     self.assertTrue(test_cell.alive)
Exemplo n.º 18
0
def fancy_pattern_demo():
    # https://de.wikipedia.org/wiki/Conways_Spiel_des_Lebens#Andere_Objekte
    a_game = GameBoard(33)
    a_game = fancy_pattern(a_game)
    for i in range(55):
        print(a_game)
        sleep(0.1)
        a_game.progress()
Exemplo n.º 19
0
 def __init__(self):
     self.board = GameBoard()
     self.human = Human('O')
     difficulty = int(
         input(
             "Enter a difficulty from 1 to 6.\nYou can go higher, but performance will take longer.\n> "
         ))
     showScores = input("Show scores? (y/n)> ")
     self.ai = AI('X', difficulty, showScores)
Exemplo n.º 20
0
 def __init__(self, num_level):
     self.level = num_level
     self.shape = Shape()
     self.next_shape = Shape()
     self.gameboard = GameBoard(WHITE, self.shape.block_list[0].size)
     self.last_time = time.perf_counter()
     self.slow_activation_time = time.perf_counter()
     self.done_level = False
     self.start_time = time.perf_counter()
Exemplo n.º 21
0
def game_simulation(board):
    simulation_board = GameBoard(board)
    total_reward = 0
    for i in range(MAX_ROUND_NUMBER):
        choice = greedy_policy(simulation_board.board, 0, [], target_net, best=True)
        choice2d = deflatten_action(choice)
        reward = simulation_board.proceed_next_state(choice2d[0], choice2d[1])
        total_reward += reward * gamma_rate ** (i + 1)
    return simulation_board.board, total_reward
Exemplo n.º 22
0
 def __init__(self, game_mode):
     self.exit = False
     self.screen = pygame.display.get_surface()
     self.screen.fill((0, 0, 0))
     self.drawableObjects = []
     self.userBoard = GameBoard()
     self.shipBox = GameShipContainer()
     self.drawSelectedShip = False
     self.flyingDutch = Boat("./res/img/boat_one_mast.png", 0, 0, 0)
Exemplo n.º 23
0
def generateBoards(parent1, parent2, boardSize):
    """
    This function creates two new children from the parent boards provided
    :param parent1: First parent
    :param parent2: second parent
    :param boardSize: size of the board
    :return: the children boards
    """
    board1 = GameBoard(boardSize)
    board2 = GameBoard(boardSize)
    slice = boardSize // 2
    board1.array = numpy.concatenate(
        (parent1.array[:slice], parent2.array[slice:]))
    board2.array = numpy.concatenate(
        (parent2.array[:slice], parent1.array[slice:]))
    board1.queens = parent1.queens[:slice] + parent2.queens[slice:]
    board2.queens = parent2.queens[:slice] + parent1.queens[slice:]
    return board1, board2
Exemplo n.º 24
0
def move():
    # print('Calculating Move (Last Move = {0})'.format(last_move))
    data = bottle.request.json
    # move = nextMove(data)
    # print(move)
    # directions = ['right', 'left', 'up', 'down']

    g = GameBoard(data['width'], data['height'])
    g.populate_board(data)

    values = []
    right = g.get_right()
    values.append(right)
    left = g.get_left()
    values.append(left)
    up = g.get_up()
    values.append(up)
    down = g.get_down()
    values.append(down)

    maximum = max(values)
    indices = [i for i, v in enumerate(values) if v == maximum]

    tmp_arr = []
    if len(indices) == 1:
        if indices[0] == 0:
            move = 'right'
        elif indices[0] == 1:
            move = 'left'
        elif indices[0] == 2:
            move = 'up'
        else:
            move = 'down'
    if len(indices) > 1:
        for i in indices:
            if i == 0: # right
                tmp_arr.append((g.get_value_for_right_side(), 'right'))
            if i == 1:
                tmp_arr.append((g.get_value_for_left_side(), 'left'))
            if i == 2:
                tmp_arr.append((g.get_value_for_up(), 'up'))
            if i == 3:
                tmp_arr.append((g.get_value_for_down(), 'down'))

            maximum = max(tmp_arr)
            move = maximum[1]

    # g.print_board()
    # print('The move picked is: ', move)
    # print('The values picked is: ', values)
    # print('The tmp_arr picked is: ', tmp_arr)
    print(move)

    return {
        'move': move,
        'taunt': 'You Fish!'
    }
Exemplo n.º 25
0
    def __init__(self, player1, player2):
        self.size = (3, 3)

        self.board = GameBoard(
            size=self.size
        )  #, preset=[['X', 'O', 'X'],['O', ' ', 'X'],[' ', ' ', 'O']])
        self.players = [player1, player2]
        self.turn_num = 0
        self.current_player = 0
        self.all_boards = []
Exemplo n.º 26
0
 def get_board_creations_per_second(self, num_boards):
     boards = []
     board = GameBoard(self.num_columns, self.num_rows)
     t0 = time.time()
     for _ in range(num_boards):
         new_board = board.make_copy()
         boards.append(new_board)
     t1 = time.time()
     total_time = t1 - t0
     return num_boards / total_time
Exemplo n.º 27
0
 def test_death_by_overpopulation(self):
     game = GameBoard(5)
     test_cell = game.get_cell(2, 2)
     test_cell.alive = True
     game.get_cell(2, 3).alive = True
     game.get_cell(1, 2).alive = True
     game.get_cell(3, 3).alive = True
     game.get_cell(1, 1).alive = True
     game.progress()
     self.assertFalse(test_cell.alive)
Exemplo n.º 28
0
 def getSuccessorStates(self):
     """返回接下来的子状态列表, 和getActions[1]顺序是对应的"""
     successorStates = []
     for row, col in self.board.getEmpty():
         gb = GameBoard(anotherBoard=self.board)
         nextPlayer = 3 - self.player  # 把player编号互换1和2
         gb.addStone(self.player, row, col)
         nextState = State(gb, nextPlayer)
         successorStates.append(nextState)
     return successorStates
Exemplo n.º 29
0
 def __init__(self):
     self.stable_mode = True
     self.gameboard = GameBoard()
     pygame.init()
     self.testFont = pygame.font.Font('freesansbold.ttf', 20)
     self.screen = pygame.display.set_mode(
         ((self.gameboard.column_dim + 5) * cell_size,
          self.gameboard.row_dim * cell_size), 0, 32)
     ## round means how many bottom rows are added
     self.round = 0
Exemplo n.º 30
0
class GameConsole:
    """"
    Introduction screen showing options to play

    :param Screen: Screen in GUI. Tasked by screen manager.
    """
    player_one = "X"
    player_two = "O"
    set_game = " "
    __not_tie = True

    @staticmethod
    def game_choice(game):
        """"
        Sets the game choice chosen by player.

        :param game: takes in the game type
        :return: sets the type of game
        """
        global set_game
        set_game = game
        return set_game

    game = GameBoard(player_one, player_two)
    game.print_board()

    @staticmethod
    def update_board(player_number, position):
            """"
            Updates the GameBoard from whats input in Graphics

            :param player_number: player's number (if computer, computer is always player2)
            :param position: letter position on the board
            """
            if set_game == "player_vs_computer":
                Graphics.GameScreen.com_exist = True
            if (GameConsole.game.check_win(1) != 1 and GameConsole.game.check_win(2) != 2
                    and GameConsole.__not_tie):
                print("Player #%d's turn\n" % player_number)
                if position is None or position > 8 or position < 0:
                    print("Error")
                else:
                    GameConsole.game.edit_board(player_number, position)
                    if Graphics.GameScreen.player_number == 1:
                        Graphics.GameScreen.player_number = 2
                    else:
                        Graphics.GameScreen.player_number = 1
            if GameConsole.game.check_tie():
                print("Game Tied!")
                GameConsole.__not_tie = False
                Graphics.GameScreen.player_tie = True
            if GameConsole.game.check_win(1) == 1:
                Graphics.GameScreen.player_one_win = True
            if GameConsole.game.check_win(2) == 2:
                Graphics.GameScreen.player_two_win = True