Beispiel #1
0
def connect_four(player1, player2):
    """ Plays a game of Connect Four between the two specified players,
        and returns the Board object as it looks at the end of the game.
        inputs: player1 and player2 are objects representing Connect Four
                  players (objects of the Player class or a subclass of Player).
                  One player should use 'X' checkers and the other should
                  use 'O' checkers.
    """
    # Make sure one player is 'X' and one player is 'O'.
    if player1.checker not in 'XO' or player2.checker not in 'XO' \
       or player1.checker == player2.checker:
        print('need one X player and one O player.')
        return None

    print('Welcome to Connect Four!')
    print()
    board = Board(6, 7)
    print(board)
    
    while True:
        if process_move(player1, board) == True:
            return board

        if process_move(player2, board) == True:
            return board
Beispiel #2
0
def p1vsai():
    clearScreen()

    diff = difficulty()
    time.sleep(1.5)

    board = Board()
    turns_taken = 0
    possible_nums = [str(i) for i in range(1, 10)]
    last_move, AI_XO, p1_XO = chooseXO()

    while turns_taken < 9:
        clearScreen()
        board.print_board()

        if last_move == "p1":
            print("Bot's turn")
            time.sleep(1.5)
            if diff == "E":
                possible_nums = AI_turn_easy(board, possible_nums, AI_XO,
                                             p1_XO)
            elif diff == "H":
                possible_nums = AI_turn_hard(board, possible_nums, AI_XO,
                                             p1_XO)
            elif diff == "I":
                possible_nums = AI_turn_impossible(board, possible_nums, AI_XO,
                                                   p1_XO)
            last_move = "AI"

        elif last_move == "AI":
            print("Player 1's turn")
            possible_nums = p1_turn(board, possible_nums, p1_XO)
            last_move = "p1"

        win = check_win(board, turns_taken)
        if win == None:
            pass
        else:
            break

        turns_taken += 1

    clearScreen()
    board.print_board()

    if win == AI_XO:
        print("Bot wins. You lose :(")
        time.sleep(1.5)
    elif win == p1_XO:
        print("You win :) Congratulations!")
        time.sleep(1.5)
    else:
        print("It was a draw")
        time.sleep(1.5)

    time.sleep(1.5)
Beispiel #3
0
def aivsai():
    clearScreen()

    board = Board()
    turns_taken = 0
    possible_nums = [str(i) for i in range(1, 10)]
    print("Bot 1 is 'O' and will go first")
    print("Bot 2 is 'X' and will go second")
    time.sleep(2)
    AI1_XO = "O"
    AI2_XO = "X"
    last_move = "AI2"

    AI1_moves = [AI_turn_easy, AI_turn_hard, AI_turn_impossible]
    AI2_moves = [AI_turn_easy, AI_turn_hard, AI_turn_impossible]

    while turns_taken < 9:
        clearScreen()
        board.print_board()

        if last_move == "AI2":
            print("Bot 1's Turn")
            time.sleep(1.5)
            possible_nums = random.choice(AI1_moves)(board, possible_nums,
                                                     AI1_XO, AI2_XO)
            last_move = "AI1"
        elif last_move == "AI1":
            print("Bot 2's turn")
            time.sleep(1.5)
            possible_nums = random.choice(AI2_moves)(board, possible_nums,
                                                     AI2_XO, AI1_XO)
            last_move = "AI2"

        win = check_win(board, turns_taken)
        if win == None:
            pass
        else:
            break

        turns_taken += 1

    clearScreen()
    board.print_board()

    if win == AI1_XO:
        print("Bot 1 wins!")
        time.sleep(1.5)
    elif win == AI2_XO:
        print("Bot 2 wins!")
        time.sleep(1.5)
    else:
        print("It was a draw")
        time.sleep(1.5)

    time.sleep(1.5)
Beispiel #4
0
    def setUp(self):
        self.testboard = Board()

        # WHITE FIGURES

        # self.test_white_pawn1 = Figure("p", "white", "A2", self.testboard)
        # self.test_white_pawn2 = Figure("p", "white", "B2", self.testboard)
        # self.test_white_pawn3 = Figure("p", "white", "C2", self.testboard)
        # self.test_white_pawn4 = Figure("p", "white", "D2", self.testboard)
        # self.test_white_pawn5 = Figure("p", "white", "E2", self.testboard)
        # self.test_white_pawn6 = Figure("p", "white", "F2", self.testboard)
        # self.test_white_pawn7 = Figure("p", "white", "G2", self.testboard)
        # self.test_white_pawn8 = Figure("p", "white", "H2", self.testboard)

        self.test_white_rook_left = Figure("r", "white", "A1", self.testboard)
        self.test_white_rook_right = Figure("r", "white", "H1", self.testboard)
        self.test_white_knight_left = Figure("k", "white", "B1",
                                             self.testboard)
        self.test_white_knight_right = Figure("k", "white", "G1",
                                              self.testboard)
        self.test_white_bishop_left = Figure("b", "white", "C1",
                                             self.testboard)
        self.test_white_bishop_right = Figure("b", "white", "F1",
                                              self.testboard)
        self.test_white_queen = Figure("Q", "white", "D1", self.testboard)
        self.test_white_king = Figure("K", "white", "E1", self.testboard)

        # BLACK FIGURES

        self.test_black_pawn1 = Figure("p", "black", "A7", self.testboard)
        self.test_black_pawn2 = Figure("p", "black", "B7", self.testboard)
        self.test_black_pawn3 = Figure("p", "black", "C7", self.testboard)
        self.test_black_pawn4 = Figure("p", "black", "D7", self.testboard)
        self.test_black_pawn5 = Figure("p", "black", "E7", self.testboard)
        self.test_black_pawn6 = Figure("p", "black", "F7", self.testboard)
        self.test_black_pawn7 = Figure("p", "black", "G7", self.testboard)
        self.test_black_pawn8 = Figure("p", "black", "H7", self.testboard)

        self.test_black_rook_left = Figure("r", "black", "A8", self.testboard)
        self.test_black_rook_right = Figure("r", "black", "H8", self.testboard)
        self.test_black_knight_left = Figure("k", "black", "B8",
                                             self.testboard)
        self.test_black_knight_right = Figure("k", "black", "G8",
                                              self.testboard)
        self.test_black_bishop_left = Figure("b", "black", "C8",
                                             self.testboard)
        self.test_black_bishop_right = Figure("b", "black", "F8",
                                              self.testboard)
        self.test_black_queen = Figure("Q", "black", "D8", self.testboard)
        self.test_black_king = Figure("K", "black", "E8", self.testboard)

        self.testboard.update()
        # print(self.testboard)

        self.results = []
    def play_game(self):
        P1 = Player(self.player_1_type, 1)
        P2 = Player(self.player_2_type, 2)
        B = Board()
        player_list = [P1, P2]
        turn_count = 0
        error_count = 0
        winner_id = ''

        while turn_count < 42:
            current_player = player_list[turn_count % 2]
            move, piece = current_player.make_move_master(B.board_dict)
            # print("You are here. This is move we got coming in: " + str(move))

            if B.is_error(move) != 0:
                if B.is_error(int(move)) == 1:
                    print('ERROR CODE 1 move not int!')
                    error_count += 1
                    # print('Error count: ' + str(error_count))
                    continue
                if B.is_error(int(move)) == 2:
                    print('ERROR CODE 2 move not 1-7!')
                    error_count += 1
                    # print('Error count: ' + str(error_count))
                    if current_player.player_type == 'Human':
                        continue
                    else:
                        break
                if B.is_error(int(move)) == 3:
                    # print('ERROR CODE 3 move off board')
                    error_count += 1
                    # print('Error count: ' + str(error_count))
                    continue
            error_count = 0

            B.board_move(move, piece)
            if self.print_status == 2:
                B.print_board()
            if B.is_win() is True:
                winner_id = (turn_count % 2) + 1
                print("Game Won!!!")
                break
            turn_count += 1
        if winner_id == '':
            winner_id = 3

        if self.print_status == 1 or self.print_status == 2:
            print("FINAL BOARD: ")
            B.print_board()
            print(B.board_dict)
            print('')
            print(B.move_list)

        return winner_id, B.board_dict
Beispiel #6
0
 def __init__(self,
              numRows: int,
              numCols: int,
              blankChar: str = '*',
              possibleTotalHits: int = None) -> None:
     self.blankChar = blankChar
     self.possibleTotalHits = None  # this will obviously need to change to what is included in config. file
     self.board = Board(numRows, numCols, blankChar)
     self.players = []
     self.maxX = numRows - 1
     self.maxY = numCols - 1
     self._curPlayerTurn = 0
Beispiel #7
0
 def __init__(self,
              puzzle_size,
              clue_str,
              symmetry=None,
              starting_cell=None,
              find_all=True):
     '''Object that holds this puzzles details and inputs'''
     self.puzzle_size = puzzle_size
     self.clue_str = clue_str + 'Y'
     self.symmetry = symmetry
     self.starting_cell = starting_cell
     self.find_all = find_all
     self.first_board = Board(initialize_first_grid(self.puzzle_size), self)
Beispiel #8
0
def takeTurns(gameDisplay, columns, username, teams, target, boardWidth,
              boardHeight):
    '''
        - Creates basic gameplay loop.
        - Each team/color takes it in turns to add a chip to the board. The user
          can click to add a chip. On a CPU's turn, the 'findMove()' function
          from the 'Board' object is called.
    '''
    exitGame = False
    teamsIter = cycle(iter(teams))
    clock = pygame.time.Clock()
    for i in range(np.random.randint(1, len(teams) + 1)):
        next(teamsIter)
    turn = next(teamsIter)
    board = Board(columns, columns, teams, target)

    while not exitGame:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exitGame = True
        if board.checkWin() == None and board.availableColumns != []:
            if turn != username:
                newColumn = board.findMove(turn)
                board.addChip(newColumn, turn)
                turn = next(teamsIter)
            else:
                if event.type == pygame.MOUSEBUTTONDOWN:
                    posx = event.pos[0]
                    move = int(math.floor(posx / (boardWidth / columns)))
                    if move in board.availableColumns:
                        board.addChip(move, turn)
                        turn = next(teamsIter)
            drawBoard(gameDisplay, board)

        if board.checkWin() != None:
            print('{} wins!!'.format(turn))
        elif board.availableColumns == []:
            print("It's a draw!!")

        pygame.display.update()
        clock.tick(25)
    def make_move_smart_1(self, board_dict):
        # Just checks if next move is winning, or blocks an opposing winning move
        temp_B = Board()
        temp_B.board_dict = board_dict.copy()

        for i in range(1, 8):
            temp_B.board_move(i, self.player_piece)
            if temp_B.is_win() is True:
                return i
            else:
                temp_B.board_dict = board_dict.copy()

        for i in range(1, 8):
            temp_B.board_move(i, self.opposing_piece)
            if temp_B.is_win() is True:
                return i
            else:
                temp_B.board_dict = board_dict.copy()

        user_move = random.randint(1, 7)
        return user_move
Beispiel #10
0
from board_class import Board
from file_io import get_maze_key_from_file, write_dict_to_file, read_dict_from_file, write_set_to_file
import matplotlib.pyplot as plt

maze = Board()
print("\n")
num_sol_gen = {}

num_of_mazes_per_iter = 10
iterations = 10

for i in range(iterations):
    maze_set = maze.build_random_maze2(num_of_mazes=num_of_mazes_per_iter,
                                       verbose=True,
                                       size_board=(9, 9),
                                       min_moves=30,
                                       adl_checks=True,
                                       adl_check_threshold=50)
    print("\n")

    write_set_to_file(maze_set)

    print("\n")
    for key, value in sorted(maze_set.items()):
        num_sol_gen[key] = len(value)
    print("This pass generated these mazes: ")
    print(num_sol_gen)
    print("\n")

# Generate the histogram.
keys = num_sol_gen.keys()
from board_class import Board, Minotaur, Player
import file_io

# maze_key = file_io.read_dict_from_file("mazes/6x6.txt")[47][0]
maze_key = {'size_board': (5, 5), 'walls': [((0, 1), (1, 1)), ((1, 0), (1, 1)), ((1, 1), (1, 2)), ((1, 2), (2, 2)), ((1, 3), (1, 4)), ((2, 2), (2, 3)), ((2, 3), (2, 4)), ((3, 0), (3, 1)), ((3, 1), (3, 2)), ((3, 2), (3, 3)), ((3, 3), (3, 4)), ((4, 0), (4, 1)), ((4, 1), (4, 2)), ((4, 3), (4, 4))], 'player_start': (1, 4), 'mino_start': (4, 4), 'goal': (4, 4), 'solution': ['left', 'up', 'right', 'right', 'right', 'right', 'up', 'left', 'left', 'up', 'up', 'left', 'left', 'right', 'right', 'down', 'down', 'right', 'right', 'down', 'up', 'left', 'left', 'up', 'up', 'right', 'right', 'left', 'left', 'left', 'left', 'down', 'down', 'down', 'down', 'right', 'right', 'right', 'right'], 'sol_length': 39, 'seed': 7188903436156103517}
maze = Board(maze_key)

player = Player(maze)
mino = Minotaur(maze)

maze.visualize_board()

solution = maze_key["solution"]

game_end = False
moves = 0

for step in solution:
	# Get player move
	player_move = step

	# Update player location
	location_before = player.location
	player.move(player_move)
	location_after = player.location
	print("Player moved from {before} to {after}.".format(before=location_before, after=location_after))
	maze.visualize_board()

	moves += 1

	# Minotaur's turn
    def make_move_smart_2(self, board_dict):
        # Checks if can force a win
        # print("Start of Move Analysis")
        # Test comment
        win_count = 0
        bad_move_list = []
        good_move_list = []
        possible_move_list = []
        temp_B = Board()

        for i in range(1, 8):
            if temp_B.is_error(i) == 3:
                continue
            else:
                possible_move_list.append(i)

        # temp_B.print_board()
        for move in possible_move_list:
            temp_B.board_dict = board_dict.copy()
            # print("Original Board: ")
            # temp_B.print_board()
            # print("TEMP MOVE FIRST LAYER: " + str(i))
            temp_B.board_move(i, self.player_piece)
            # print("Level 1 Move Board: ")
            if temp_B.is_win() is True:
                # print("Level 1 Win Found")
                return i
            win_count = 0
            for k in range(1, 8):
                temp_B.board_move(k, self.opposing_piece)
                if temp_B.is_win() is True:
                    # print("This move would lead to a guaranteed loss: " + str(i))
                    # temp_B.print_board()
                    bad_move_list.append(i)
                    temp_B.take_back()
                    break
                for p in range(1, 8):
                    temp_B.board_move(p, self.player_piece)
                    # print("TEMP MOVE 3: " + str(p))
                    if temp_B.is_win() is True:
                        win_count += 1
                        # print("Level 3 Win found below. Level 3 Win Count: " + str(win_count))
                        # temp_B.print_board()
                        if win_count == 7:
                            print(
                                "ABSOLUTE WIN FOUND- Aren't you a clever boy: "
                                + str(i))
                            # Bug where move returned is off-board, because player wins regardless
                            good_move_list.append(i)
                        temp_B.take_back()
                        break

                    temp_B.take_back()
                temp_B.take_back()
            temp_B.take_back()

        # Checks first to make sure not missing an oponent has a winning move
        temp_B.board_dict = board_dict.copy()
        for i in range(1, 8):
            temp_B.board_move(i, self.opposing_piece)
            if temp_B.is_win() is True:
                return i
            else:
                temp_B.board_dict = board_dict.copy()

        # Solves bug of constantly returning a move that is off-board
        temp_B.board_dict = board_dict.copy()
        for user_move in good_move_list:
            if temp_B.is_error(user_move) == 0:
                return user_move

        # Solves bug if no good move left
        if len(bad_move_list) >= 6:
            # print("THERE ARE NO GOOD MOVES BREAK")
            user_move = random.randint(1, 7)
            return user_move

        # BUG HERE: When you get near end of game, there is only one column to move in. But it's
        # in the bad move list, so it gets trapped in the While loop below

        # If still no good move
        user_move = random.randint(1, 7)
        while user_move in bad_move_list:

            print("You do get here")
            user_move = random.randint(1, 7)

        # print("Random Move playing: " + str(user_move))
        return user_move
 def make_move_human(self, board_dict):
     temp_B = Board()
     temp_B.board_dict = board_dict.copy()
     temp_B.print_board()
     user_move = input("Make move: ")
     return int(user_move)
Beispiel #14
0
p = pawn, Q = queen, K = king, k = knight, b = bishop, r = rook

TO DO LIST:

- GUI
- rochade, en passant, promotion, check, checkmate

- TURN STARTS HERE -

"""

from figure_class import Figure, move
from board_class import Board

my_board = Board()

# WHITE FIGURES

white_pawn1 = Figure("p", "white", "A2", my_board)
white_pawn2 = Figure("p", "white", "B2", my_board)
white_pawn3 = Figure("p", "white", "C2", my_board)
white_pawn4 = Figure("p", "white", "D2", my_board)
white_pawn5 = Figure("p", "white", "E2", my_board)
white_pawn6 = Figure("p", "white", "F2", my_board)
white_pawn7 = Figure("p", "white", "G2", my_board)
white_pawn8 = Figure("p", "white", "H2", my_board)

white_rook_left = Figure("r", "white", "A1", my_board)
white_rook_right = Figure("r", "white", "H1", my_board)
white_knight_left = Figure("k", "white", "B1", my_board)
Beispiel #15
0
			for new_option in maze.get_move_options(player_location)["player"]:
				move_queue.append([new_option, current_state, move_list[:]])
			pass
		elif game_end is True and game_win is False:
			# In this case, the Minotaur killed the player. No new options are added to the queue. 
			# print("Game loss.")
			pass
		elif game_end is True and game_win is True:
			# The solver has found a solution. 
			move_list.append(option)
			return True, move_list
		
		# maze.visualize_board()
		# print(move_queue)

	# If the end of the while loop is reached, then there is no solution. 
	return False, []



maze = Board(maze_file="mazes/level_20.txt")
maze.visualize_board()
print("\n")
solvable, solution = solve(maze)
if solvable:
	print("The maze is solvable in {} moves with the following solution: ".format(len(solution)))
	print(solution)
else:
	print("The maze is not solvable.")
maze.visualize_board()
Beispiel #16
0
    if counter == 1:
        state = -state
    state = state.reshape((1, 9))
    return state


memory = Memory(3000)
model = Model(0.001)

epsilon = 0.9
with tf.Session() as sess:
    sess.run(model.var_init)
    for game in range(10000):
        if game % 100 == 0:
            print(game)
        board = Board()
        winner = ''
        counter = 0
        symbols = ['X', 'O']
        #we need to store samples temporarily because we don't get their values till the end of each game
        samples = [
        ]  #each sample contains state, action, reward, and next state
        while winner == '':
            state = state_from_board(board, counter)

            action = choose_action(epsilon, state, model, sess)

            current_sample = []
            current_sample.append(state)
            current_sample.append(action)
Beispiel #17
0
 def __init__(self):
     self.board = Board()