예제 #1
0
def main():
    print('Starting a new game...!')
    newgamestate = connectfour.new_game_state()
    ##    connectfour.BOARD_ROWS = int(input('How many columns would you like to play with?: '))
    ##    connectfour.BOARD_COLUMNS = int(input('How many rows would you like to play with?: '))
    while True:
        if newgamestate.turn == 'R':
            red_turn = int(
                input(
                    '''Red's turn!\n Please enter the corresponding numbers for desired action\n 1.) Drop piece, 2.)Pop Piece: '''
                ))
            if red_turn == 1:
                red_drop = int(
                    input(
                        "Enter number of column to drop red piece from 0 to {}: "
                        .format(connectfour.BOARD_COLUMNS - 1)))
                if red_drop > connectfour.BOARD_COLUMNS or red_drop < 0:
                    raise connectfour.InvalidConnectFourMoveError()
                else:
                    newgamestate = connectfour.drop_piece(
                        newgamestate, red_drop)
                    print_board(newgamestate)
            else:
                red_pop = int(
                    input(
                        'Enter column number to pop red piece from 0 to {}: '.
                        format(connectfour.BOARD_COLUMNS - 1)))
                if red_pop > connectfour.BOARD_COLUMNS or red_pop < 0:
                    raise connectfour.InvalidConnectFourMoveError()
                else:
                    newgamestate = connectfour.pop_piece(newgamestate, red_pop)
                    print_board(newgamestate)
        else:
            yellow_turn = int(
                input(
                    '''Yellow's turn!\n Please enter the corresponding numbers for desired action\n 1.) Drop piece, 2.)Pop Piece: '''
                ))
            if yellow_turn == 1:
                yellow_drop = int(
                    input(
                        "Enter column number to drop yellow piece from 0 to {}: "
                        .format(connectfour.BOARD_COLUMNS - 1)))
                newgamestate = connectfour.drop_piece(newgamestate,
                                                      yellow_drop)
                print_board(newgamestate)
            else:
                yellow_pop = int(
                    input(
                        'Enter column number to pop yellow piece from 0 to {}: '
                        .format(connectfour.BOARD_COLUMNS - 1)))
                newgamestate = connectfour.pop_piece(newgamestate, yellow_pop)
                print_board(newgamestate)
        if connectfour.winning_player(newgamestate) == 'R':
            print('RED player has won! Congradulations!')
            break
        elif connectfour.winning_player(newgamestate) == 'Y':
            print('YELLOW player has won! Congradulations!')
            break
def s_move_pop(gamestate, socket):
    try:
        pop = eval(input('please select a row(0-5): '))
    except SyntaxError:
        print('invalid input')
        return s_move_pop(gamestate, socket)
    except NameError:
        print('invalid input')
        return s_move_pop(gamestate, socket)
    try:
        gamestate = gamestate._replace(
            board=connectfour.pop_piece(gamestate, pop).board,
            turn=connectfour._opposite_turn(gamestate.turn))
        display_board(gamestate)
        mode = 'POP'
        if gamestate.turn == 'R':
            wait_player_move(mode, pop, socket)
        elif gamestate.turn == 'Y':
            wait_server_move(mode, pop, socket)
    except ValueError:
        print('\n' + str(pop) + ' Not avalid column')
        s_move_pop(gamestate, socket)
    except connectfour.ConnectFourGameOverError:
        pass
    except connectfour.InvalidConnectFourMoveError:
        print(
            'not a valid move. cannot pop other player\'s peice and you cannot pop empty columns\n'
        )
        s_move_pop(gamestate, socket)
def s_move_pop(gamestate,socket):
    try:
        pop = eval(input('please select a row(0-5): '))
    except SyntaxError:
        print('invalid input')
        return s_move_pop(gamestate,socket)
    except NameError:
        print('invalid input')
        return s_move_pop(gamestate,socket)
    try :
        gamestate = gamestate._replace(board = connectfour.pop_piece(gamestate, pop).board,
                                              turn= connectfour._opposite_turn(gamestate.turn))   
        display_board(gamestate)
        mode = 'POP'
        if gamestate.turn == 'R':
            wait_player_move(mode, pop,socket)
        elif gamestate.turn == 'Y':
            wait_server_move(mode, pop,socket)
    except ValueError:
        print('\n' + str(pop) + ' Not avalid column')
        s_move_pop(gamestate,socket)
    except connectfour.ConnectFourGameOverError:
        pass
    except connectfour.InvalidConnectFourMoveError:
        print('not a valid move. cannot pop other player\'s peice and you cannot pop empty columns\n')
        s_move_pop(gamestate,socket)
def main_program() -> None:
##    while True:
    State = C.new_game_state()
    while True:
        winner = C.winning_player(State)
        F.new_board(State.board)
        if winner != C.NONE:
            break
        try:
            print("It's " + F.full_name(State.turn) + " player's turn. ", end = '')
            command = input(F.Menu).upper()
            if command == 'A':
                column_number = int(input('please enter the column number: '))
                State = C.drop_piece(State, column_number - 1)
                print()
            elif command == 'B':
                column_number = int(input('please enter the column number: '))
                State = C.pop_piece(State, column_number - 1)
                print()
            else:
                F.invalid_command(command)
        except C.InvalidConnectFourMoveError:
            print('\nInvaild command. Please try again.\n')
        except ValueError:
            print('\nError. Column number must be between 1 and 7.\n') 
        except C.ConnectFourGameOverError:
            print('\nError. Game is over.\n')
    if winner == C.RED:
        print('Red player wins!')
    elif winner == C.YELLOW:
        print('Yellow player wins!')
    print()
예제 #5
0
    def __init__(self: object):
        """Init new game"""

        self.state = connectfour.new_game_state()

        while True:
            self.print_state()

            winner = connectfour.winning_player(self.state)
            if winner != connectfour.NONE:
                if winner == connectfour.RED:
                    print("Red is the winner!")
                elif winner == connectfour.YELLOW:
                    print("Yellow is the winner!")
                break

            input_is_vaild = False
            while not input_is_vaild:
                action = self._get_input()
                try:
                    if action["action"] == "d":
                        self.state = connectfour.drop_piece(
                            self.state, action["column_number"] - 1)
                    elif action["action"] == "p":
                        self.state = connectfour.pop_piece(
                            self.state, action["column_number"] - 1)
                    else:
                        raise connectfour.InvalidConnectFourMoveError()
                    input_is_vaild = True
                except:
                    print("Sorry, invalid move.")
예제 #6
0
def _move_network(
    gameState: connectfour.ConnectFourGameState, move: str,
    connection: connectfour_protocol.connectFourConnection
) -> connectfour.ConnectFourGameState:
    'This function determines what move the current player would like to do'
    while True:
        try:
            column = int(
                input('Which column (1 - ' + str(connectfour.BOARD_COLUMNS) +
                      '):  '))
            if column > 0 and column <= connectfour.BOARD_COLUMNS:
                if move == 'D':
                    gameState = connectfour.drop_piece(gameState, column - 1)
                    connectfour_protocol.sendMove(connection, 'DROP', column)
                    break
                elif move == 'P':
                    gameState = connectfour.pop_piece(gameState, column - 1)
                    connectfour_protocol.sendMove(connection, 'POP', column)
                    break
            else:
                print('Invalid column, please try again.\n')
        except:
            print('Invalid input, please try again.')
            break
    return gameState
def move_pop(gamestate):
    try:
        pop = eval(input('please select a row(0-5): '))
    except SyntaxError:
        print('invalid input')
        return move_pop(gamestate)
    except NameError:
        print('invalid input')
        return move_pop(gamestate)
    try:
        gamestate = gamestate._replace(
            board=connectfour.pop_piece(gamestate, pop).board,
            turn=connectfour._opposite_turn(gamestate.turn))
        display_board(gamestate)
        return move_ops(gamestate)
    except ValueError:
        print('\n' + str(drop) + ' Not avalid column')
        move_pop(gamestate)
    except connectfour.ConnectFourGameOverError:
        print('Game Over')
        print('winner: ' + connectfour.winning_player(gamestate))
        return
    except connectfour.InvalidConnectFourMoveError:
        print('Column is full')
        move_pop(gamestate)
예제 #8
0
def game_UI() -> None:
    '''Main function, the user interface'''
    state = common.start_game()  # Print and creates the starting state
    while True:
        common.print_turn(state)
        while True:
            INPUT = common.piece_input()
            if INPUT[0] == 'DROP':  # Dropping a piece
                try:
                    state = connectfour.drop_piece(state, INPUT[1])
                    break
                except connectfour.InvalidMoveError:
                    print('Sorry, your move is invalid. Please try again.')
                except connectfour.GameOverError:
                    print('Sorry, the game is already over.')
            elif INPUT[0] == 'POP':  # Popping a piece
                try:
                    state = connectfour.pop_piece(state, INPUT[1])
                    break
                except connectfour.InvalidMoveError:
                    print('Sorry, your move is invalid. Please try again.')
                except connectfour.GameOverError:
                    print('Sorry, the game is already over.')
        print()
        common.print_board(state.board)
        if common.decide_over(state) == True:
            # Print out the winner and stop the game if
            # there is a winner, continue otherwise.
            break
예제 #9
0
def give_turn(game_state:namedtuple,command:str,col:int):
    '''
    Processes the users and AI commmand and updates the game state
    '''    
    if command.upper()=='DROP':               
        game_state=connectfour.drop_piece(game_state,col-1)
    elif command.upper()=='POP':
        game_state=connectfour.pop_piece(game_state,col-1)
    return game_state
예제 #10
0
def pop_or_drop(game_state: connectfour.ConnectFourGameState, action: str,
                move: int) -> connectfour.ConnectFourGameState:
    '''give player an option whether to pop for drop a piece and execute the command'''
    if action == POP:
        new_game_state = connectfour.pop_piece(game_state, move)
        return new_game_state
    else:
        new_game_state = connectfour.drop_piece(game_state, move)
        return new_game_state
예제 #11
0
def pop_or_drop(
    game_state: connectfour.ConnectFourGameState, action: str, move: int
) -> connectfour.ConnectFourGameState:
    """give player an option whether to pop for drop a piece and execute the command"""
    if action == POP:
        new_game_state = connectfour.pop_piece(game_state, move)
        return new_game_state
    else:
        new_game_state = connectfour.drop_piece(game_state, move)
        return new_game_state
예제 #12
0
def pop_n_drop(GAME: object, user_input, column_number):
    try:
        if user_input == "DROP":
            GAME = connectfour.drop_piece(GAME, (int(column_number) - 1))
        if user_input == "POP":
            GAME = connectfour.pop_piece(GAME, (int(column_number) - 1))
        print_board(GAME)
    except:
        print("Column number must be from 1-7")
    return GAME
예제 #13
0
파일: linkui.py 프로젝트: solomc1/python
def pop_option(game_state:ConnectFourGameState,col:int)-> ConnectFourGameState:
    '''if user chooses p, pop the piece'''

    try:
        
        game_state = connectfour.pop_piece(game_state,int(col)-1)
    except e:
        print('Unsucessful')
        raise e
        
    return game_state
def _handle_drop_n_pop(board: ConnectFourGameState,
                       yellow_turn: list) -> ConnectFourGameState:
    if yellow_turn[0] == 'DROP':
        column = int(yellow_turn[1])
        board = connectfour.drop_piece(board, column - 1)
        return board
    elif yellow_turn[0] == 'POP':
        column = int(yellow_turn[1])
        board = connectfour.pop_piece(board, column - 1)
        return board
    else:
        print('Boo is cute!')
def computer_move(server_counter_action : str, current_state:'current game state'):
    # split the server's action into action and column
    action_column = server_counter_action.split()
    action = action_column[0]
    column = action_column [1]
    # drop/pop a piece and update the current state of the game
    if action == 'DROP':
        current_state = connectfour.drop_piece(current_state,int(column) - 1)
        return current_state
    elif action == 'POP':
        current_state = connectfour.pop_piece(current_state,int(column) - 1)
        return current_state
예제 #16
0
def check_red(newgamestate, user_str):

    red_turn = user_str
    valid_move_check(red_turn[1], 0, connectfour.BOARD_COLUMNS - 1)
    if (red_turn[0][:-2]) == 'DROP':
        newgamestate = connectfour.drop_piece(newgamestate, red_turn[1] - 1)
        return print_board(newgamestate)
    elif (red_turn[0][:-2]) == 'POP':
        newgamestate = connectfour.pop_piece(newgamestate, red_turn[1] - 1)
        return print_board(newgamestate)
    elif check_game_progress == True:
        return True
예제 #17
0
def mainsingle():
    """this is the main function frame that operate in the single player status"""
    ConnectFourGameState = connectfour.new_game_state()
    print('Game start!\n')
    printboard(ConnectFourGameState)
    print("Enter your move(for example, 'DROP column#' or 'POP column#'\n")
    while True:
        #check if there is a winner
        winnernum = connectfour.winning_player(ConnectFourGameState)
        if winnernum == connectfour.NONE:
            if not checkboard(ConnectFourGameState):
                while True:
                    if ConnectFourGameState[1] == int(1):
                        print("Red turn.")
                    elif ConnectFourGameState[1] == int(2):
                        print("Yellow turn.")
                    try:
                        originalcommand = input("Enter your move: ")
                        order, colnum = command(originalcommand)
                        if (order == 'POP'
                                or order == 'pop') or (order == 'DROP'
                                                       or order == 'drop'):
                            break
                        else:
                            print(
                                "\nInput format error (must be 'DROP column#' or 'POP column#')\n"
                            )

                    except:
                        print(
                            "\nInput format error (must be 'DROP column#' or 'POP column#')\n"
                        )
                if order == 'DROP' or order == 'drop':
                    try:
                        ConnectFourGameState = connectfour.drop_piece(
                            ConnectFourGameState, colnum - 1)
                    except connectfour.InvalidMoveError:
                        print('\nSorry, this column is already full\n')

                if order == 'POP' or order == 'pop':
                    try:
                        ConnectFourGameState = connectfour.pop_piece(
                            ConnectFourGameState, colnum - 1)
                    except connectfour.InvalidMoveError:
                        print('\nSorry, this column is empty\n')
                printboard(ConnectFourGameState)
            else:
                print('\nThe board is already full, no winner.\n')
                return
        else:
            break
    printwinner(winnernum)
예제 #18
0
def _player_pop(game_board: ConnectFourGameState):
    '''
    Takes a column number and performs a pop in specified column
    '''
    try:
        column = int(input('Please enter a column to pop: '))
        column_num = column - 1
        game_board = connectfour.pop_piece(game_board, column_num)
    except:
        print('ERROR INVALID COLUMN \nTRY AGAIN')
    finally:
        current_board(game_board)
        return game_board
예제 #19
0
def _current_game(current_game: connectfour.ConnectFourGameState,
                  internet=False,
                  connection=None) -> None:
    '''Makes the moves on the game board'''
    _print_board(current_game)
    if internet == False:
        while connectfour.winning_player(current_game) == connectfour.NONE:
            split_command = handle_game_menu(current_game).split()
            if split_command[0] == 'DROP':
                current_game = connectfour.drop_piece(
                    current_game,
                    int(split_command[1]) - 1)
            elif split_command[0] == 'POP':
                current_game = connectfour.pop_piece(current_game,
                                                     int(split_command[1]) - 1)
            _print_board(current_game)
        if connectfour.winning_player(current_game) == 'R':
            print('Game Over. Red Player has won.')
        elif connectfour.winning_player(current_game) == 'Y':
            print('Game Over. Yellow Player has won.')
    elif internet == True:
        status = 'OKAY'
        while status != 'WINNER_RED' or 'WINNER_YELLOW':
            current_game, status = _send_game_move(connection, current_game)
            _print_board(current_game)
            if connectfour.winning_player(current_game) == 'R':
                status = 'WINNER_RED'
                break
            elif connectfour.winning_player(current_game) == 'Y':
                status = 'WINNER_YELLOW'
                break
            print('\n')
            print("Recieving AI's move...")
            current_game = _recieve_game_move(connection, current_game)
            print('Move recieved.')
            input("Please enter a key to see the AI's move")
            _print_board(current_game)
            if connectfour.winning_player(current_game) == 'R':
                status = 'WINNER_RED'
                break
            elif connectfour.winning_player(current_game) == 'Y':
                status = 'WINNER_YELLOW'
                break
        if status == 'WINNER_RED':
            print('Game Over. Red Player has won.')
        elif status == 'WINNER_YELLOW':
            print('Game Over. Yellow Player has won.')
        else:
            print(status)
            print('Error. Ending Game.')
예제 #20
0
def mainsingle():  #type in 'asfa' return error
    """this is the main function frame that operate in the single player status"""
    ConnectFourGameState = connectfour.new_game_state()
    print('Game start!\n')
    printboard(ConnectFourGameState)
    originalcommand = input(
        "Enter your move(for example, 'DROP column#' or 'POP column#'): ")
    # instruct player only once about the input format
    # print board once at the beginning
    # print whose turn it is
    # ? ask user to drop and pop (dont change this one now, lets finish other parts first)
    # accept both capital and lower case
    while True:
        #check if there is a winner
        winnernum = connectfour.winning_player(ConnectFourGameState)
        if winnernum == connectfour.NONE:
            if not checkboard(ConnectFourGameState):
                while True:
                    try:
                        originalcommand = input("Enter your move: ")
                        commandlist = originalcommand.split()
                        order = commandlist[0]
                        colnum = int(commandlist[1])
                        if (order == 'POP') or (order == 'DROP'):
                            break
                    except:
                        print(
                            "Input format error (must be 'DROP column#' or 'POP column#')"
                        )
                if order == 'DROP':
                    try:
                        ConnectFourGameState = connectfour.drop_piece(
                            ConnectFourGameState, colnum - 1)
                    except (connectfour.InvalidMoveError):
                        print('Sorry, this column is already full')

                if order == 'POP':
                    try:
                        ConnectFourGameState = connectfour.pop_piece(
                            ConnectFourGameState, colnum - 1)

                    except (connectfour.InvalidMoveError):
                        print('Sorry, this column is empty')
                printboard(ConnectFourGameState)
            else:
                print('The board is already full, no winner.')
                return
        else:
            break
    printwinner(winnernum)
예제 #21
0
def apply_move(game_state: connectfour.ConnectFourGameState,
               move: str) -> connectfour.ConnectFourGameState:
    """ Apply player's move to current board
    """
    col = int(move[move.find(" ") + 1:])

    if move.lower().startswith("drop"):
        print()
        return connectfour.drop_piece(game_state, col - 1)
    elif move.lower().startswith("pop"):
        print()
        return connectfour.pop_piece(game_state, col - 1)
    else:
        print("INVALID MOVE")
예제 #22
0
def move(game_state: connectfour.ConnectFourGameState, column_number: int,
         move_type: str) -> None:
    '''Applies a move to the game state.'''

    try:
        if move_type == 'drop':
            return connectfour.drop_piece(game_state, column_number - 1)
        elif move_type == 'pop':
            return connectfour.pop_piece(game_state, column_number - 1)
    except connectfour.InvalidConnectFourMoveError:
        print("Invalid move.")
        return game_state
    except connectfour.ConnectFourGameOverError:
        print("The game is already over!")
        return game_state
def execute_move(current_game: namedtuple, drop_location: int, turn: str) -> namedtuple:
    if 'DROP' in turn:
        if drop_location > 0 and drop_location <= 7:
            new_current_game = connectfour.drop_piece(current_game, drop_location - 1)
            return new_current_game
        else:
            raise connectfour.InvalidConnectFourMoveError
    elif 'POP' in turn:
        if drop_location > 0 and drop_location <= 7:
            new_current_game = connectfour.pop_piece(current_game, drop_location - 1)
            return new_current_game
        else:
            raise connectfour.InvalidConnectFourMoveError
    else:
        raise connectfour.InvalidConnectFourMoveError
예제 #24
0
def _recieve_game_move(
    connection: ICFSP32._I32CFSPConnection,
    current_game: connectfour.ConnectFourGameState
) -> connectfour.ConnectFourGameState:
    '''Recieves Game Move'''
    recieve_command = ICFSP32._recieve_message(connection)
    split_recieve_command = recieve_command.split()
    if split_recieve_command[0] == 'DROP':
        current_game = connectfour.drop_piece(
            current_game,
            int(split_recieve_command[1]) - 1)
        return current_game
    elif split_recieve_command[0] == 'POP':
        current_game = connectfour.pop_piece(current_game,
                                             int(split_recieve_command[1]) - 1)
        return current_game
예제 #25
0
def make_move(game_state: connectfour.ConnectFourGameState, column_number: int,
              move_type: str) -> None:
    """
        Was going to initially add a While True at the top so that it would keep asking the 
        user to make a valid move. 
        But Edge Case: 
            if one of the columns is filled and they choose to drop than it would
            keep asking it to drop instead of going back to choose the type of move
    """
    try:
        if move_type == "drop":
            return connectfour.drop_piece(game_state, column_number - 1)
        elif move_type == "pop":
            return connectfour.pop_piece(game_state, column_number - 1)
    except:
        print("Invalid Move")
        return game_state
예제 #26
0
def move_network_ai(
    gameState: connectfour.ConnectFourGameState,
    connection: connectfour_protocol.connectFourConnection
) -> connectfour.ConnectFourGameState:
    'This function receives the status of the network AI and updates the gameState accordingly.'
    status = connectfour_protocol.serverStatus(connection)
    status = status.split()
    print('Current player is:  AI (Yellow)')
    if status[0] == 'DROP':
        print('AI drops in column ' + status[1])
        gameState = connectfour.drop_piece(gameState, int(status[1]) - 1)
    elif status[0] == 'POP':
        print('AI pops column ' + status[1])
        gameState = connectfour.pop_piece(gameState, int(status[1]) - 1)
    else:
        print('Move was invalid. Try again.')
    return gameState
예제 #27
0
def pop_or_drop(board: ConnectFourGameState,
                column: int) -> ConnectFourGameState:
    respond = True
    while respond:
        answer = input("Pop or Drop? (P/D) ")
        answer = answer.upper()
        if answer == 'P':
            board = connectfour.pop_piece(board, column - 1)
            display_board(board[0])
            respond = False
            return board
        elif answer == 'D':
            board = connectfour.drop_piece(board, column - 1)
            display_board(board[0])
            respond = False
            return board
        else:
            print('Not a valid command! Please type P or D!\n')
예제 #28
0
def make_move(game, move):
    if move.split()[0] == 'DROP':
        
        column_number = int(move.split()[1])
        try:
            game = connectfour.drop_piece(game, column_number - 1)
        except:
            print('Invalid move.')
        
    if move.split()[0] == 'POP':
        
        column_number = int(move.split()[1])
        try:
            game = connectfour.pop_piece(game, column_number - 1)
        except:
            print('Invalid move.')
    
    return game
def server_turn(server_move, gameState):
    '''
    Handles the system when it is the server's turn. Uses the input received from
    the server to drop or pop a piece. Returns the updated board and the current
    game state
    '''
    print('\nIt is Player', gameState.turn + "'s turn.")
            
    if server_move[0] == 'DROP':
        gameState = connectfour.drop_piece(gameState, int(server_move[-1])-1)
        ConnectFour_ui.print_gameboard(gameState)
        print('\nPlayer Y {}ped a piece in column {}.'.format(server_move[0].lower(), server_move[-1]))
        print('\n---------------------------------\n')
        
    elif server_move[0] == 'POP':
        gameState = connectfour.pop_piece(gameState, int(server_move[-1])-1)
        ConnectFour_ui.print_gameboard(gameState)
        print('\nPlayer Y {}ped a piece in column {}.'.format(server_move[0].lower(), server_move[-1]))
        print('\n---------------------------------\n')

    return gameState
예제 #30
0
def game_move(s: 'gamestate', message: str):
    '''Takes a game state and and message as arguments and drops or pops a piece if the message
       is DROP or POP respectively and returns the game state
    '''
    try:
        move = message.split()[0]
        column_number = int(message.split()[1])
        if len(message.split()) > 2:
            raise ValueError
        if move == 'DROP':
            return connectfour.drop_piece(s, column_number - 1)
        elif move == 'POP':
            return connectfour.pop_piece(s, column_number - 1)
        else:
            return None
    except connectfour.InvalidConnectFourMoveError:
        return None
    except ValueError:
        print('Invalid Column Number')
    except IndexError:
        return None
예제 #31
0
def DROP1(pop_or_drop, new):
    #new = connectfour.new_game_state()
    while True:
        if pop_or_drop[0:5] == "DROP ":
            try:
                n = int(pop_or_drop[5])
                column_number = n - 1
                drop = connectfour.drop_piece(new, column_number)
            except connectfour.InvalidMoveError:
                print("a move cannot be made in the given column because the column is filled already")
                break
            except connectfour.GameOverError:
                print("Game is over! Please enter E to exit the game or enter N to start a new game")
                continue
            except ValueError:
                print("Invalid input, try again")
                continue
            new = drop
            print_board(drop)
            return new

        elif pop_or_drop[0:4] == "POP ":
            try:
                p = int(pop_or_drop[4])
                pop_number = p - 1
                drop = connectfour.pop_piece(new, pop_number)
            except connectfour.InvalidMoveError:
                print("a piece cannot be popped from the bottom of the given column because the column is empty or because the piece at the bottom of the column belongs to the other player")
                break
            except connectfour.GameOverError:
                print("Game is over! Please enter E to exit the game or enter N to start a new game")
                continue
            except ValueError:
                print("Invalid input, try again")
                continue
            new = drop
            print_board(drop)
            return new
        break
예제 #32
0
def _send_game_move(
    connection: ICFSP32._I32CFSPConnection,
    current_game: connectfour.ConnectFourGameState
) -> connectfour.ConnectFourGameState:
    '''Sends Game Move'''
    status = 'INVALID'
    while status == 'INVALID':
        message = ICFSP32._recieve_message(connection)
        send_command = handle_game_menu(current_game)
        split_command = send_command.split()
        ICFSP32._send_message(connection, send_command)
        recieve_message = ICFSP32._recieve_message(connection)
        if recieve_message == 'OKAY' or 'WINNER_RED' or 'WINNER_YELLOW':
            if split_command[0] == 'DROP':
                current_game = connectfour.drop_piece(
                    current_game,
                    int(split_command[1]) - 1)
                return current_game, recieve_message
            elif split_command[0] == 'POP':
                current_game = connectfour.pop_piece(current_game,
                                                     int(split_command[1]) - 1)
                return current_game, recieve_message
예제 #33
0
def userinterface():
    '''This is the main user interface of the sever version'''
    try:
        Connectionfour = connect_four_socket.connect('woodhouse.ics.uci.edu',
                                                     4444)
    #except doesn't work???
    #except connect_four_socket.ServerNoResponseError():
    #pass
    except:
        print('No response from server')
    ConnectFourGameState = startstatecheck(Connectionfour)
    while True:
        winnernum = connectfour.winning_player(ConnectFourGameState)
        if winnernum == connectfour.NONE:
            if ConnectFourGameState.turn == 1:
                '''This if statement handle client's move'''
                order, colnum = userinput()
                if order.upper() == 'DROP':
                    try:
                        ConnectFourGameState = connectfour.drop_piece(
                            ConnectFourGameState, colnum - 1)
                    except connectfour.InvalidMoveError:
                        print('Sorry, this column is already full')
                if order.upper() == 'POP':
                    try:
                        ConnectFourGameState = connectfour.pop_piece(
                            ConnectFourGameState, colnum - 1)
                    except connectfour.InvalidMoveError:
                        print('Sorry, this column is empty')
                connect_four_common.printboard(ConnectFourGameState)
            elif ConnectFourGameState.turn == 2:
                '''This if statement handle server's move'''
                ConnectFourGameState = servermove(ConnectFourGameState,
                                                  Connectionfour, order,
                                                  colnum)
        else:
            return
def move(
    action: str, column_number: int,
    game_state: connectfour.ConnectFourGameState
) -> connectfour.ConnectFourGameState:
    '''
    Update the game state according to players' move.
    '''
    if action == "DROP":
        try:
            current_game_state = connectfour.drop_piece(
                game_state, column_number - 1)
        except:
            print("Not a valid move. (The column is full)")
            return game_state
    elif action == "POP":
        try:
            current_game_state = connectfour.pop_piece(game_state,
                                                       column_number - 1)
        except:
            print(
                "Not a valid move. (The column is empty or the piece belongs to the other player)"
            )
            return game_state
    return current_game_state
def user_action_input(current_state: tuple, column_specified: int):
    # ask the player to specify their action (drop/ pop) in the column they selected.
    # Ask the user to specify again if the action is invalid move on the selected column.
    while True:
        try:
            user_act_input = input('Please Select--- Drop or Pop  : ').lower()
            if user_act_input == 'pop':
                return (connectfour.pop_piece(current_state,
                                              int(column_specified - 1)),
                        column_specified, user_act_input)

            elif user_act_input == 'drop':
                return (connectfour.drop_piece(current_state,
                                               int(column_specified - 1)),
                        column_specified, user_act_input)

            else:
                print('not a valid command action!')
        except:
            print(
                'invalid move on {} column or invalid column. Please enter another column.'
                .format(column_specified))
            current_state = turn(current_state)
            return current_state
def move_pop(gamestate):
    try:
        pop = eval(input('please select a row(0-5): '))
    except SyntaxError:
        print('invalid input')
        return move_pop(gamestate)
    except NameError:
        print('invalid input')
        return move_pop(gamestate)
    try :
        gamestate = gamestate._replace(board = connectfour.pop_piece(gamestate, pop).board,
                                              turn= connectfour._opposite_turn(gamestate.turn))   
        display_board(gamestate)
        return move_ops(gamestate)
    except ValueError:
        print('\n' + str(drop) + ' Not avalid column')
        move_pop(gamestate)
    except connectfour.ConnectFourGameOverError:
        print('Game Over')
        print('winner: ' + connectfour.winning_player(gamestate))
        return
    except connectfour.InvalidConnectFourMoveError:
        print('Column is full')
        move_pop(gamestate)
예제 #37
0
def servermove(ConnectFourGameState, Connectionfour, order,
               colnum) -> connectfour.ConnectFourGameState:
    '''send the order to server and return its reply'''
    connect_four_socket.write(Connectionfour, order + ' ' + str(colnum))
    connect_four_socket.checkOKAY(Connectionfour)
    reply = connect_four_socket.readline(Connectionfour).split()
    replyorder = reply[0]
    replycolnum = int(reply[1])
    print('The server decides to', reply[0], 'at column', reply[1])
    if replyorder.upper() == 'DROP':
        try:
            ConnectFourGameState = connectfour.drop_piece(
                ConnectFourGameState, replycolnum - 1)
        except connectfour.InvalidMoveError:
            print('Sorry, this column is already full')
    if replyorder.upper() == 'POP':
        try:
            ConnectFourGameState = connectfour.pop_piece(
                ConnectFourGameState, replycolnum - 1)
        except connectfour.InvalidMoveError:
            print('Sorry, this column is empty')
    connect_four_socket.expect(Connectionfour, 'READY')
    connect_four_common.printboard(ConnectFourGameState)
    return ConnectFourGameState
예제 #38
0
def operate_move(game, move, column):
    '''with move and column info, operate action on the game board'''
    if move == "DROP":
        try:
            new_game = connectfour.drop_piece(game, column-1)
            _create_game_board(new_game.board)
        except:
            print("Enter a valid command")
            new_game = game

        finally:
            return new_game
    
    elif move == "POP":
        try:
            new_game = connectfour.pop_piece(game, column-1)
            _create_game_board(new_game.board)

        except:
            print("Enter a valid command")
            new_game = game
            
        finally:
            return new_game
def main_program(host, port) -> None:
    username = _P_.confirm_username()
    game_socket = socket.socket()
    try:
        print('\nconnecting to server...\n')
        game_socket.connect((host, port))
        print('Connected successfully.\n')
        _P_.send_message(game_socket, str('I32CFSP_HELLO ' + username))
        reply1 = _P_.receive_message(game_socket)
        print(reply1, end = '\n\n')
        _P_.send_message(game_socket, 'AI_GAME')
        reply2 = _P_.receive_message(game_socket)
        print(reply2, end = '\n\n')
    except ConnectionRefusedError:
        print('Invalid port')
        return 'Invalid'
##    while True:
    State = _X_.new_game_state()
    while True:
        winner = _X_.winning_player(State)
        _F_.new_board(State.board)
        if winner != _X_.NONE:
            break
        try:
            _F_.turn(State.turn)
            command = input(_F_.Menu).upper()
            if command == 'A':
                column_number = int(input('please enter the column number: '))
                State = _X_.drop_piece(State, column_number - 1)
                print()
                AI = _P_.AI(game_socket, 'A', column_number).split()
##                print(AI)
##                _C_.new_board(State.board)
##                print()
##                _N_.AI_turn(State.turn)
                if AI[0] == 'DROP':
                    State = _X_.drop_piece(State, int(AI[1]) - 1)
                elif AI[0] == 'POP':
                    State = _X_.pop_piece(State, int(AI[1]) - 1)
            elif command == 'B':
                column_number = int(input('please enter the column number: '))
                State = _X_.pop_piece(State, column_number - 1)
                print()
                AI = _P_.AI(game_socket, 'B', column_number).split()
##                print(AI)
##                _C_.new_board(State.board)
##                print()
##                _N_.AI_turn(State.turn)
                if AI[0] == 'DROP':
                    State = _X_.drop_piece(State, int(AI[1]) - 1)
                elif AI[0] == 'POP':
                    State = _X_.pop_piece(State, int(AI[1]) - 1)
            else:
                _F_.invalid_command(command)
        except _X_.InvalidConnectFourMoveError:
            print('\nInvaild command. Please try again.\n')
        except ValueError:
            print('\nError. Column number must be between 1 and 7.\n') 
        except _X_.ConnectFourGameOverError:
            print('\nError. Game is over.\n')
    if winner == _X_.RED:
        print('Red player wins!')
    elif winner == _X_.YELLOW:
        print('Yellow player wins!')
##        restart = input('\nPlay again?  (Y/N)').upper()
##        if restart == 'Y':
##            print('game restart!\n\n')
##            State = _X_.new_game_state()
##        elif restart == 'N':
##            print('\nThanks for playing, Bye!')
##            break
##        else:
##            _C_.invalid_command(restart)
    print('\nGame is over.\nThanks for playing, Bye!')
예제 #40
0
def _pop_piece(state, column):
    column = int(column)
    state = connectfour.pop_piece(state, column)
    print_board(state.board)
    return state
def auto_pop(gamestate, col):
    gamestate = gamestate._replace(board = connectfour.pop_piece(gamestate, int(col)).board,
                                              turn= connectfour._opposite_turn(gamestate.turn)) 
    return gamestate
def _pop_piece(state,column):
    column = int(column)
    state = connectfour.pop_piece(state, column)
    print_board(state.board)
    return state