コード例 #1
0
ファイル: main.py プロジェクト: msarfati/dummy-projects
def main():
    print("===:: THE DUEL ::===\n\
    Welcome to The Duel, a small, turn-based RPG-style dueling game.")
    global TURN_COUNTER
    global PLAYER_MENU
    global ENEMY_NAME
    TURN_COUNTER = int(1)
    PLAYER_MENU = 'Moves: | (1) Slash | (2) Thrust | (3) Heal | (0) Forfeit |\nSelect:> '

    # p = Dueler(name=nameGen())
    p = Dueler(name=raw_input("What is your name? "))
    e = Dueler(name=nameGen(), isAI=True)
    ai = AI(e)
    ENEMY_NAME = str(e.name)

    while p.hp > 0 and e.hp > 0:
        'Main event thread'
        gameStatus(p, e, TURN_COUNTER)
        pSelect = isValid()
        action(p, e, pSelect) # Player action
        action(e, p, ai.select()) # Enemy action
        if (p.hp < 0) or (e.hp < 0):
            whoWon = lambda a, b: a.name if a.hp > b.hp else b.name
            whoWon = whoWon(p, e)
            print("{} {}wins in {} turns.\nThanks for playing!".format(
                whoWon,
                "(you) " if p.name == whoWon else "(enemy) ",
                TURN_COUNTER))
            raise SystemExit
        TURN_COUNTER += 1
コード例 #2
0
ファイル: main.py プロジェクト: GitSid2k/Skillfactory
    def __init__(self, size=6):
        self.size = size
        pl = self.random_board()
        co = self.random_board()
        co.hid = True

        self.ai = AI(co, pl)
        self.us = User(pl, co)
コード例 #3
0
ファイル: test_ai.py プロジェクト: raghv0/tic-tac-toe
def test_second_turn_center_opening(player_mark):
    other_mark = Game.FIRST_PLAYER_MARK
    ai = AI(player_mark)
    board = Board()
    board._rows = [[' ', ' ', ' '], [' ', other_mark, ' '], [' ', ' ', ' ']]
    for _ in range(100):
        assert ai._second_turn(board.representation()) in product((0, 2),
                                                                  (0, 2))
コード例 #4
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()
コード例 #5
0
ファイル: test_ai.py プロジェクト: raghv0/tic-tac-toe
def test_center(player_mark):
    other_mark = other_player(player_mark)
    ai = AI(player_mark)
    board = Board()
    board._rows = [[other_mark, ' ', ' '], [' ', player_mark, ' '],
                   [' ', ' ', other_mark]]
    assert ai._center(board.representation()) is None

    board._rows = [[player_mark, ' ', ' '], [' ', ' ', ' '],
                   [other_mark, ' ', other_mark]]
    assert ai._center(board.representation()) == (1, 1)
コード例 #6
0
ファイル: test_ai.py プロジェクト: raghv0/tic-tac-toe
def test_block_fork(player_mark):
    other_mark = other_player(player_mark)
    ai = AI(player_mark)
    board = Board()
    board._rows = [[other_mark, ' ', ' '], [' ', player_mark, ' '],
                   [' ', ' ', other_mark]]
    assert ai.turn(board.representation()) in ((0, 2), (2, 0))

    board._rows = [[player_mark, ' ', ' '], [' ', other_mark, ' '],
                   [' ', ' ', other_mark]]
    assert ai.turn(board.representation()) in ((0, 2), (2, 0))
コード例 #7
0
ファイル: test_ai.py プロジェクト: raghv0/tic-tac-toe
def test_create_fork(player_mark):
    other_mark = other_player(player_mark)
    ai = AI(player_mark)
    board = Board()
    board._rows = [[player_mark, ' ', ' '], [' ', other_mark, ' '],
                   [' ', ' ', player_mark]]
    assert ai.turn(board.representation()) in ((2, 0), (0, 2))

    board._rows = [[player_mark, ' ', ' '], [player_mark, ' ', ' '],
                   [' ', ' ', ' ']]
    assert ai._fork(board.representation()) == (1, 1)
コード例 #8
0
ファイル: test_ai.py プロジェクト: raghv0/tic-tac-toe
def test_empty_corner(player_mark):
    other_mark = other_player(player_mark)
    ai = AI(player_mark)
    board = Board()
    board._rows = [[other_mark, ' ', ' '], [' ', player_mark, ' '],
                   [' ', ' ', ' ']]
    assert ai._empty_corner(board.representation()) in ((0, 2), (2, 2), (2, 0))

    board._rows = [[player_mark, ' ', ' '], [' ', ' ', ' '],
                   [other_mark, ' ', other_mark]]
    assert ai._empty_corner(board.representation()) == (0, 2)

    board._rows = [[player_mark, ' ', player_mark], [' ', ' ', ' '],
                   [other_mark, ' ', other_mark]]
    assert ai._empty_corner(board.representation()) is None
コード例 #9
0
ファイル: test_ai.py プロジェクト: raghv0/tic-tac-toe
def test_empty_edge(player_mark):
    other_mark = other_player(player_mark)
    ai = AI(player_mark)
    board = Board()
    board._rows = [[other_mark, ' ', ' '], [' ', player_mark, ' '],
                   [' ', player_mark, ' ']]
    assert ai._empty_edge(board.representation()) in ((0, 1), (1, 2), (1, 0))

    board._rows = [[player_mark, other_mark, ' '], [' ', ' ', ' '],
                   [other_mark, player_mark, other_mark]]
    assert ai._empty_edge(board.representation()) in ((1, 2), (1, 0))

    board._rows = [[player_mark, player_mark, player_mark],
                   [other_mark, ' ', player_mark],
                   [other_mark, other_mark, other_mark]]
    assert ai._empty_edge(board.representation()) is None
コード例 #10
0
ファイル: board.py プロジェクト: katzuv/mancala-no-graphics
 def reset(self):
     self.ai_player = self.ai_player = AI(
         'lower')  # TODO: Check if could be deleted
     self._upper_pits = [4] * 6
     self._lower_pits = [4] * 6
     self._upper_store = 0
     self._lower_store = 0
     self.extra_turn = False
     self.current_player = 'upper'
     self.has_match_ended = False
コード例 #11
0
ファイル: board.py プロジェクト: katzuv/mancala-no-graphics
 def __init__(self):
     """Instantiate a Mancala board."""
     self.ai_player = self.ai_player = AI('lower')
     self._upper_pits = [4] * 6
     self._lower_pits = [4] * 6
     self._upper_store = 0
     self._lower_store = 0
     self.extra_turn = False
     self.current_player = 'upper'
     self.has_match_ended = False
コード例 #12
0
def player_type_chooser(mancala: Mancala, player_side: str):
    """Return the type of a player.
    :return: the type chosen of a player
    """
    while True:
        player_type = input(
            f'Enter the type of the {player_side} player: 1 for Human or 3 for AI: '
        )
        if player_type == '1':
            return Console(player_side)
        if player_type == '2':
            return AI(player_side)
        if player_type == '3':
            return Graphics(player_side, mancala.board)
        else:
            print('You did not enter a valid number')
コード例 #13
0
ファイル: test_ai.py プロジェクト: raghv0/tic-tac-toe
def test_second_turn_corner_opening(player_mark):
    other_mark = Game.FIRST_PLAYER_MARK
    ai = AI(player_mark)
    board = Board()
    board._rows = [[other_mark, ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']]
    assert ai._second_turn(board.representation()) == (1, 1)

    board._rows = [[' ', ' ', other_mark], [' ', ' ', ' '], [' ', ' ', ' ']]
    assert ai._second_turn(board.representation()) == (1, 1)

    board._rows = [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', other_mark]]
    assert ai._second_turn(board.representation()) == (1, 1)

    board._rows = [[' ', ' ', ' '], [' ', ' ', ' '], [other_mark, ' ', ' ']]
    assert ai._second_turn(board.representation()) == (1, 1)
コード例 #14
0
ファイル: test_ai.py プロジェクト: raghv0/tic-tac-toe
def test_win(player_mark):
    ai = AI(player_mark)
    board = Board()
    board._rows = [[player_mark, ' ', player_mark], [' ', ' ', ' '],
                   [' ', ' ', ' ']]
    assert ai.turn(board.representation()) == (0, 1)

    board._rows = [[' ', player_mark, ' '], [' ', player_mark, ' '],
                   [' ', ' ', ' ']]
    assert ai.turn(board.representation()) == (2, 1)

    board._rows = [[' ', ' ', ' '], [' ', player_mark, ' '],
                   [' ', ' ', player_mark]]
    assert ai.turn(board.representation()) == (0, 0)

    board._rows = [[' ', ' ', player_mark], [' ', ' ', ' '],
                   [player_mark, ' ', ' ']]
    assert ai.turn(board.representation()) == (1, 1)
コード例 #15
0
ファイル: test_ai.py プロジェクト: raghv0/tic-tac-toe
def test_block(player_mark):
    other_mark = other_player(player_mark)
    ai = AI(player_mark)
    board = Board()
    board._rows = [[other_mark, ' ', other_mark], [' ', ' ', ' '],
                   [' ', ' ', ' ']]
    assert ai.turn(board.representation()) == (0, 1)

    board._rows = [[' ', other_mark, ' '], [' ', other_mark, ' '],
                   [' ', ' ', ' ']]
    assert ai.turn(board.representation()) == (2, 1)

    board._rows = [[' ', ' ', ' '], [' ', other_mark, ' '],
                   [' ', ' ', other_mark]]
    assert ai.turn(board.representation()) == (0, 0)

    board._rows = [[' ', ' ', other_mark], [' ', ' ', ' '],
                   [other_mark, ' ', ' ']]
    assert ai.turn(board.representation()) == (1, 1)

    board._rows = [[player_mark, ' ', ' '], [other_mark, other_mark, ' '],
                   [player_mark, ' ', other_mark]]
    assert ai.turn(board.representation()) == (1, 2)
コード例 #16
0
ファイル: ai.py プロジェクト: tuahk/term2048
number_of_runs = 50
goal = 2048
train = 0

args = sys.argv
print(len(args))
if len(args) > 1:
    board_size = int(args[1])
    number_of_runs = int(args[2])
    train = int(args[3]) # 0 for NO and 1 for YES
    alpha = float(args[4])
    gamma = float(args[5])
    epsilon = float(args[6])
    goal = int(args[7])
#    print(board_size,number_of_runs,train,alpha,gamma,epsilon)
    ai = AI(board_size, train, alpha, gamma ,epsilon)
else:
    ai = AI(board_size)

if train == 0 and os.stat('states').st_size!=0:
    pkl_file = open('states', 'r')
    ai.states = pickle.load(pkl_file)
    
results = run(ai.q_learning_ai,number_of_runs, goal=goal, size=board_size)
ai.print_states()

if train != 0:
    pkl_file = open('states', 'w+')
    pickle.dump(ai.states, pkl_file, pickle.HIGHEST_PROTOCOL)
pkl_file.close()
コード例 #17
0
ファイル: main.py プロジェクト: GitSid2k/Skillfactory
class Game:
    def __init__(self, size=6):
        self.size = size
        pl = self.random_board()
        co = self.random_board()
        co.hid = True

        self.ai = AI(co, pl)
        self.us = User(pl, co)

    def random_board(self):
        board = None
        while board is None:
            board = self.random_place()
        return board

    def random_place(self):
        lens = [3, 2, 2, 1, 1, 1, 1]
        board = Board(size=self.size)
        attempts = 0
        for l in lens:
            while True:
                attempts += 1
                if attempts > 2000:
                    return None
                ship = Ship(Dot(randint(0, self.size), randint(0, self.size)), l, randint(0, 1))
                try:
                    board.add_ship(ship)
                    break
                except BoardWrongShipException:
                    pass
        board.begin()
        return board

    def greet(self):
        print("-" * 27)
        print("      Приветсвуем вас")
        print("          в игре")
        print("        морской бой")
        print("-" * 27)
        print(" формат ввода: x y ")
        print(" x - номер строки  ")
        print(" y - номер столбца ")

    def loop(self):
        num = 0
        while True:
            print("-" * 27)
            print("Доска пользователя:")
            print(self.us.board)
            print("-" * 27)
            print("Доска компьютера:")
            print(self.ai.board)
            if num % 2 == 0:
                print("-" * 27)
                print("Ходит пользователь!")
                repeat = self.us.move()
            else:
                print("-" * 27)
                print("Ходит компьютер!")
                repeat = self.ai.move()
            if repeat:
                num -= 1

            if self.ai.board.count == 7:
                print("-" * 27)
                print("Пользователь выиграл!")
                break

            if self.us.board.count == 7:
                print("-" * 27)
                print("Компьютер выиграл!")
                break
            num += 1

    def start(self):
        self.greet()
        self.loop()
コード例 #18
0
ファイル: test_ai.py プロジェクト: raghv0/tic-tac-toe
def test_first_turn(player_mark):
    ai = AI(player_mark)
    board = Board()
    assert ai._first_turn(board.representation()) in product((0, 2), (0, 2))
コード例 #19
0
number_of_runs = 50
goal = 2048
train = 0

args = sys.argv
print(len(args))
if len(args) > 1:
    board_size = int(args[1])
    number_of_runs = int(args[2])
    train = int(args[3])  # 0 for NO and 1 for YES
    alpha = float(args[4])
    gamma = float(args[5])
    epsilon = float(args[6])
    goal = int(args[7])
    #    print(board_size,number_of_runs,train,alpha,gamma,epsilon)
    ai = AI(board_size, train, alpha, gamma, epsilon)
else:
    ai = AI(board_size)

if train == 0 and os.stat('states').st_size != 0:
    pkl_file = open('states', 'r')
    ai.states = pickle.load(pkl_file)

results = run(ai.q_learning_ai, number_of_runs, goal=goal, size=board_size)
ai.print_states()

if train != 0:
    pkl_file = open('states', 'w+')
    pickle.dump(ai.states, pkl_file, pickle.HIGHEST_PROTOCOL)
pkl_file.close()