コード例 #1
0
 def restart(self):
     """ Reinitialize the game and board after restart button is pressed """
     self.board.container.destroy()
     # create a new board object and draw board + buttons again
     self.board = ConnectFourBoard(self.parent, 50, "#ECECEC")
     self.board.draw_board()
     self.initialize_buttons()
     self.show_menu()
コード例 #2
0
    def __init__(self, parent):
        self.parent = parent

        # create a board
        self.board = ConnectFourBoard(self.parent, 50,
                                      "#ECECEC")  # hex color gray
        self.board.draw_board()

        # create all players instances
        self.player1 = Player("Player 1", "#446CB3")  # hex blue
        self.player2 = Player("Player 2", "#F4D03F")  # hex yellow
        self.initialize_buttons()
        self.show_menu()
コード例 #3
0
    def __init__(self,
            height = 9, width = 9,
            rewards = None,
            winscore = 100,
            red_player = None,
            blue_player = None,
            ai_delay = 60
            ):

        ## initialise pygame
        pygame.init()
        pygame.font.init()

        ## board
        self.board = ConnectFourBoard.EmptyBoard(height, width, rewards, winscore)

        ## interface
        self.selected_index = -1
        self.display = ConnectFourGraphics.setup_display(self.board)

        ### PLAYER SETTINGS ###
        self.red_player = red_player
        self.blue_player = blue_player
        self.ai_delay = ai_delay
        self.time_cumulative = {ConnectFourBoard.RED : 0, ConnectFourBoard.BLUE : 0}

        ## state of the game (scoreboard, who's turn it is, etc.)
        self.score_red = 0
        self.score_blue = 0
        self.winner = 0
        self.game_running = True
        self.red_turn = True

        ## draw initial board
        self.draw()
コード例 #4
0
ファイル: ConnectFourEngine.py プロジェクト: batuengin/Python
    def __init__(self,
                 height=9,
                 width=9,
                 rewards=None,
                 red_player=None,
                 blue_player=None,
                 ai_delay=60,
                 winscore=1000):

        self.field_state = [[0, 0, 0, 0, 0, 0], [1, 2, 1, 1, 0, 0],
                            [1, 0, 0, 0, 0, 0], [2, 1, 0, 0, 0, 0],
                            [1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0],
                            [0, 0, 0, 0, 0, 0]]
        self.col_heights = [0, 4, 1, 2, 1, 0, 0]

        ## initialise pygame
        pygame.init()
        pygame.font.init()

        ## board
        self.board = ConnectFourBoard.EmptyBoard(height, width, rewards,
                                                 winscore)

        ## interface
        self.selected_index = -1
        self.display = \
            ConnectFourGraphics.setup_display(self.board)

        ### PLAYER SETTINGS ###
        self.red_player = red_player
        self.blue_player = blue_player
        self.ai_delay = ai_delay

        ## state of the game (scoreboard, who's turn it is, etc.)
        self.score_red = 0
        self.score_blue = 0
        self.winner = 0
        self.score_win = 1000
        self.game_running = True
        self.red_turn = True

        ## draw initial board
        self.draw()
コード例 #5
0
ファイル: Main.py プロジェクト: yangyaoi/Connect-Four-Project
    def __init__(self, GUI):
        self.board = GUI.board
        self.GUI = GUI

    def getBoard(self):
        return self.board

    def getGUI(self):
        return self.GUI



if __name__ == '__main__':
    pygame.init()
    main = Main(G.ConnectFourGUI(B.ConnectFourBoard(6, 7)))
    while not main.board.is_game_over():
        (x,y) = C.wait_click()
        column = main.GUI.decide_column((x,y))

        if main.board.can_drop(column):
            main.board.drop(column)
            #updateGUI there

        if main.board.check_for_win():
            # show Winner view for current player
            pass
        main.board.turn = main.board.other_player()

    pygame.quit()
コード例 #6
0
def test():

    state = ConnectFourBoard(7, 6)

    assert state.getBoard() == [[EMPTY] * 7] * 6
    assert state.getPossiblePositionList(None) == [0, 1, 2, 3, 4, 5, 6]
    assert state.isWin() == None

    state.setMarker(RED, 0)
    assert state.getBoard() == [[EMPTY] * 7] * 5 + \
                               [[RED, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY]]
    assert state.getPossiblePositionList(BLUE) == [0, 1, 2, 3, 4, 5, 6]
    assert state.getNextPlayer() == BLUE

    state.setMarker(BLUE, 1)
    assert state.getBoard() == [[EMPTY] * 7] * 5 + \
                               [[RED, BLUE, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY]]
    assert state.getNextPlayer() == RED
    assert state.isFull() == False

    state.setMarker(RED, 0)
    state.setMarker(RED, 0)
    state.setMarker(RED, 0)
    assert state.isWin() == RED

    for x in range(7):
        for y in range(6):
            state.setMarker(BLUE, x)

    assert state.isFull() == True
    assert state.getPossiblePositionList(RED) == []
    assert state.isWin() == BLUE

    print "Success"
コード例 #7
0
ファイル: ConnectFourGame.py プロジェクト: sct7/ConnectFour
import ConnectFourBrain
from ConnectFourBoard import *
import ConnectFourAI

board = ConnectFourBoard()

turn = 0
v=-1
while v==-1:
	
	if turn==0:
		print board
		col=int(raw_input("Which column? "))
	else:
		col=ConnectFourAI.findSmartMove(board,1)
		print "playing " + str(col)

	board.move(col, turn)
	if turn==0: turn=1
	else: turn=0
	v=ConnectFourBrain.victory(board)

print board
print str(v) +" wins"
コード例 #8
0
ファイル: main.py プロジェクト: Jongyeop92/BoardGameAI
def runGame(autoPlay=True):

    state = ConnectFourBoard(7, 6)
    maxPlayer = False

    minTime = None
    maxTime = None
    totalTime = 0
    count = 0

    if not autoPlay:
        human = input()

        if human in [0, 1]:
            human = human == 0

    while True:

        marker = state.getNextPlayer()
        maxPlayer = not maxPlayer

        state.showBoard()

        if state.isWin():
            break

        if not autoPlay and human == maxPlayer:
            while True:
                x = input()

                if state.setMarker(marker, x):
                    break

                print marker
                print "Wrong position"
        else:
            start = time.time()

            if marker == RED:
                info = monteCarlo.get_play(state, marker)
                #info = minimax(state, 5, maxPlayer)
                #info = alphabeta(state, 6, -INFINITE, INFINITE, maxPlayer)
                pass
            else:
                info = monteCarlo.get_play(state, marker)
                #info = minimax(state, 5, maxPlayer)
                #info = alphabeta(state, 5, -INFINITE, INFINITE, maxPlayer)
                pass

            gap = time.time() - start

            if minTime == None or gap < minTime:
                minTime = gap

            if maxTime == None or gap > maxTime:
                maxTime = gap

            totalTime += gap
            count += 1

            state.setMarker(marker, info[-1])

            print marker
            print "Info:", info
            print "Gap :", gap

        print

    print "Win:", state.isWin()
    print
    print "MinTime  :", minTime
    print "MaxTime  :", maxTime
    print "MeanTime :", (totalTime / count)
    print "TotalTime:", totalTime
    print
    print "Count:", count
コード例 #9
0
]
general_tests = [
    (field_g_0, (93, 47)),
    (field_g_1, (93, 44)),
    (field_g_2, (48, 62)),
    (field_g_3, (0, 2108)),
]

tests = [
    (vertical_tests, "vertical"),
    (horizontal_tests, "horizontal"),
    (diagonal_tests, "diagonal"),
    (general_tests, "general"),
]

for (test_suite, suite_name) in tests:
    has_failure = False
    for (index, (field, (r, b))) in enumerate(test_suite):
        board = ConnectFourBoard.Board(board=field)
        (rr, bb) = board.score()
        if r == rr and b == bb:
            print('    Success (for field{})'.format(index))
        else:
            print('    FAILURE (for field{}, expected {}, got {})'.format(
                index, (r, b), (rr, bb)))
            has_failure = True
    if has_failure:
        print('Some failures in the {} tests'.format(suite_name))
    else:
        print('All {} tests succeeded'.format(suite_name))
コード例 #10
0
class ConnectFourGameApp(object):
    """
    GameApp class as controller for board and player objects

    Attributes:
    parent: (tkinter.Tk) the root window, parent of the frame
    board: instance of the board class
    unused_squares_dict: keep track of squares left on the board
    player1: instance of player class
    player2: ibid
    computer: ibid
    """
    def __init__(self, parent):
        self.parent = parent

        # create a board
        self.board = ConnectFourBoard(self.parent, 50,
                                      "#ECECEC")  # hex color gray
        self.board.draw_board()

        # create all players instances
        self.player1 = Player("Player 1", "#446CB3")  # hex blue
        self.player2 = Player("Player 2", "#F4D03F")  # hex yellow
        self.initialize_buttons()
        self.show_menu()

    def initialize_buttons(self):

        #  --- create buttons for menu ---
        self.two_players_button = tkinter.Button(
            self.board.container,
            text="PLAY WITH A FRIEND",
            width=25,
            command=self.init_two_players_game)

        self.reset_button = tkinter.Button(self.board.container,
                                           text="RESET",
                                           width=25,
                                           command=self.restart)

    def show_menu(self):
        # register buttons to board's container
        self.two_players_button.grid()

    def init_two_players_game(self):
        # reset players' squares to empty set
        self.player1.selected_sq = set()
        self.player2.selected_sq = set()

        # keep track of turns
        self.player1_turn = True

        # show reset button
        self.reset_button.grid()

        #bind play() to the leftmost button click, for macs
        #windows or other pcs might be "<Button-2>"
        self.buttonid = self.board.canvas.bind("<Button-1>", self.play)

    def restart(self):
        """ Reinitialize the game and board after restart button is pressed """
        self.board.container.destroy()
        # create a new board object and draw board + buttons again
        self.board = ConnectFourBoard(self.parent, 50, "#ECECEC")
        self.board.draw_board()
        self.initialize_buttons()
        self.show_menu()

    def add_to_player_sq(self, key, player_sq):
        """
        use key of col and row to locate position of square
        and add square to player's selected_sq set
        :param key: str concat of col and row key str
        """
        current_selected_sq = self.board.unused_squares_dict[key]
        print("current selected sq  ---->", current_selected_sq)
        print("BEFORE player selected_sq: ", player_sq)
        player_sq.add(current_selected_sq)  # player 1 = {1}
        print("AFTER player selected_sq: ", player_sq)

    def delete_used_sq(self, key):
        # delete selected sq in self.board.unused_squares_dict
        print(" ---- square to delete ---: ",
              self.board.unused_squares_dict[key])
        print("unused squares dictionary before: ",
              self.board.unused_squares_dict)
        del self.board.unused_squares_dict[key]
        print("unused squares dictionary after: ",
              self.board.unused_squares_dict)

    def play(self, event):
        """  method is invoked when the user clicks on a square
        handles click event on UI for player
        Params: event (as mouse click, with x/y coords)
        """

        # locate second column and row when player click on a square
        colrow_tuple = self.board.find_coords_of_selected_sq(event)
        # save the col and row as variable
        corner_two_col, corner_two_row = colrow_tuple[0], colrow_tuple[1]

        if (self.board.is_full(event)):
            print "COLUMN IS FULL"
            return

        if self.player1_turn == True:
            self.board.insert_piece(self.player1, event)
            if (self.board.check_for_winner(self.player1)):
                self.show_game_result(self.player1.name + " WINS!")
            self.player1_turn = False
        else:
            self.board.insert_piece(self.player2, event)
            if (self.board.check_for_winner(self.player2)):
                self.show_game_result(self.player2.name + " WINS!")
            self.player1_turn = True

        if (self.board.check_for_draw()):
            self.show_game_result("Its a TIE!!")

    def show_game_result(self, txt):
        """
        make a label to display three possible winning conditions
        params: txt to display the winner
                player_color to display matching color as player's sq
        """
        result_label = tkinter.Label(self.board.container,
                                     text=txt,
                                     width=12,
                                     height=5,
                                     foreground="red",
                                     background="gray",
                                     borderwidth=3)

        result_label.grid(row=0, column=0)
        # unbind button so player cannot click on square
        self.board.canvas.unbind("<Button-1>")