示例#1
0
def player_move(game_board: 'Connect Four Game State'):
    player_command = input('Please enter a command: ')
    column_num = int(input('Please enter a column to drop: '))
    if player_command.upper() == 'DROP':
        game_board = connectfour.drop_piece(game_board, column_num-1)
    elif player_command.upper() == 'POP':
        game_board = connectfour.drop_piece(game_board, column_num-1)
    return game_board
示例#2
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
示例#3
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.")
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 _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 s_move_drop(gamestate, socket):
    try:
        drop = eval(input('please select a row(0-5): '))
    except SyntaxError:
        print('invalid input')
        return s_move_drop(gamestate, socket)
    except NameError:
        return s_move_drop(gamestate, socket)
    try:
        gamestate = gamestate._replace(
            board=connectfour.drop_piece(gamestate, drop).board,
            turn=connectfour._opposite_turn(gamestate.turn))
        display_board(gamestate)
        print('runs drop')
        mode = 'DROP'
        if gamestate.turn == 'R':
            print('2working?')
            wait_player_move(mode, drop, socket)
        elif gamestate.turn == 'Y':
            print('working?')
            print(drop)
            wait_server_move(mode, drop, socket)
    except ValueError:
        print('\n' + str(drop) + ' Not avalid column')
        s_move_drop(gamestate, socket)
    except connectfour.ConnectFourGameOverError:
        pass
    except connectfour.InvalidConnectFourMoveError:
        print('you can only pop your own peice')
        s_move_drop(gamestate, socket)
def main():
    '''function that runs connectfour consol'''
    
    print('Welcome to ConnectFour! \n')
    print('Player 1, you are the R player. Player 2, you are the Y player')
    the_winner = connectfour.NONE
    player_one = connectfour.RED
    player_two = connectfour.YELLOW
    connectfour_function.display_board(connectfour.new_game_state().board)
    game_state = connectfour.new_game_state()

    #play the game until it ends
    while the_winner == connectfour.NONE:
        if game_state.turn == player_one:
            print('Player 1 this is your turn. please make a move')
        else:
            print('Player 2 this is your turn. please make a move')

        try:
            move = int(input('where will you drop your piece? type 1~7'))-1
            game_state = connectfour.drop_piece(game_state, move)
            connectfour_function.display_board(game_state.board)
            the_winner = connectfour.winning_player(game_state)
        except ValueError:
            print('Invalid input. Please type integer between 1 and 7')
        except connectfour.InvalidConnectFourMoveError:
            print('The column is full. Please select other column')

    #print the winner
    if the_winner == player_one:
        print('player 1, you won!')
    else:
        print('player 2, you won!')
def s_move_drop(gamestate,socket):
    try:
        drop = eval(input('please select a row(0-5): '))
    except SyntaxError:
        print('invalid input')
        return s_move_drop(gamestate,socket)
    except NameError:
        return s_move_drop(gamestate,socket)
    try :
        gamestate = gamestate._replace(board = connectfour.drop_piece(gamestate, drop).board,
                                              turn= connectfour._opposite_turn(gamestate.turn))   
        display_board(gamestate)
        print('runs drop')
        mode = 'DROP'
        if gamestate.turn == 'R':
            print('2working?')
            wait_player_move(mode, drop,socket)
        elif gamestate.turn == 'Y':
            print('working?')
            print(drop)
            wait_server_move(mode,drop,socket)
    except ValueError:
        print('\n' + str(drop) + ' Not avalid column')
        s_move_drop(gamestate,socket)
    except connectfour.ConnectFourGameOverError:
        pass
    except connectfour.InvalidConnectFourMoveError:
        print('you can only pop your own peice')
        s_move_drop(gamestate,socket)
示例#9
0
def main():
    '''function that runs connectfour consol'''

    print('Welcome to ConnectFour! \n')
    print('Player 1, you are the R player. Player 2, you are the Y player')
    the_winner = connectfour.NONE
    player_one = connectfour.RED
    player_two = connectfour.YELLOW
    connectfour_function.display_board(connectfour.new_game_state().board)
    game_state = connectfour.new_game_state()

    #play the game until it ends
    while the_winner == connectfour.NONE:
        if game_state.turn == player_one:
            print('Player 1 this is your turn. please make a move')
        else:
            print('Player 2 this is your turn. please make a move')

        try:
            move = int(input('where will you drop your piece? type 1~7')) - 1
            game_state = connectfour.drop_piece(game_state, move)
            connectfour_function.display_board(game_state.board)
            the_winner = connectfour.winning_player(game_state)
        except ValueError:
            print('Invalid input. Please type integer between 1 and 7')
        except connectfour.InvalidConnectFourMoveError:
            print('The column is full. Please select other column')

    #print the winner
    if the_winner == player_one:
        print('player 1, you won!')
    else:
        print('player 2, you won!')
示例#10
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
示例#11
0
def _drop_piece(state, column):
    try:
        column = int(column)
        state = connectfour.drop_piece(state, column)
        print_board(state.board)
    except:
        print("Error. Which column (0-6) do you want to drop?")
    finally:
        return state
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
def _drop_piece(state,column):
    try: 
        column = int(column)
        state = connectfour.drop_piece(state, column)
        print_board(state.board)
    except:
        print("Error. Which column (0-6) do you want to drop?")
    finally:
        return state
def _drop_piece(state, column):
    try:
        column = int(column)
        state = connectfour.drop_piece(state, column)
        print_board(state.board)
    except:
        print("Error.")
    finally:
        return state
def _drop_piece(state,column):
    try: 
        column = int(column)
        state = connectfour.drop_piece(state, column)
        print_board(state.board)
    except:
        print("Error.")
    finally:
        return state
def _drop_piece(state,column):
    try: 
        column = int(column)
        state = connectfour.drop_piece(state, column)
        print_board(state.board)
    except:
        print("Error. Please enter one number from 0 to 6 for column that you want to drop.")
    finally:
        return state
示例#17
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
示例#18
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
示例#19
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
示例#20
0
文件: linkui.py 项目: solomc1/python
def drop_option(game_state:ConnectFourGameState,col:int)-> ConnectFourGameState:
    '''if user chooses d, drop the piece'''

    try:
        
        game_state = connectfour.drop_piece(game_state,int(col)-1)
    except e:
        print('Unsucessful')
        raise e
        
    return game_state
示例#21
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
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
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!')
示例#24
0
def gameplay() -> None:
    board = connectfour.new_game_state()
    display_board(board[0])
    while True:
        try:
            if connectfour.winning_player(board) == ' ':
                if board[1] == 'R':
                    print('\nRed\'s Turn')
                    column = int(input('Enter column number: '))
                    if board[0][column - 1][-1] == 'R':
                        board = pop_or_drop(board, column)
                    else:
                        board = connectfour.drop_piece(board, column - 1)
                        display_board(board[0])
                else:
                    print('\nYellow\'s Turn')
                    column = int(input('Enter column number: '))
                    if board[0][column - 1][-1] == 'Y':
                        board = pop_or_drop(board, column)
                    else:
                        board = connectfour.drop_piece(board, column - 1)
                        display_board(board[0])
            else:

                player = ""
                if connectfour.winning_player(board) == 'R':
                    player += "Red Player"
                else:
                    player += "Yellow Player"
                print('Game is over! ' + player + ' is the winner!')
                break
        except IndexError:
            print('Column number you entered is not in the range of 1-7!\n')
            display_board(board[0])
        except ValueError:
            print('Not an integer!\n')
            display_board(board[0])
        except connectfour.InvalidConnectFourMoveError:
            print('Column is full! Please enter another column number!\n')
            display_board(board[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)
示例#26
0
def _player_drop(game_board: ConnectFourGameState):
    '''
    Takes a column number and performs a drop in specified column
    '''
    try:
        column = int(input('Please enter a column to drop: '))
        column_num = column - 1
        game_board = connectfour.drop_piece(game_board, column_num)
    except:
        print('ERROR INVALID COLUMN \nTRY AGAIN')
    finally:
        current_board(game_board)
        return game_board
示例#27
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")
示例#28
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)
示例#29
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.')
示例#30
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
示例#32
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
示例#33
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
示例#34
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
示例#35
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')
示例#36
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
示例#37
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
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
示例#39
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
示例#40
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
def move_drop(gamestate):
    try:
        drop = eval(input('please select a row(0-5): '))
    except SyntaxError:
        print('invalid input')
        return move_drop(gamestate)
    except NameError:
        return move_drop(gamestate)
    try :
        gamestate = gamestate._replace(board = connectfour.drop_piece(gamestate, drop).board,
                                              turn= connectfour._opposite_turn(gamestate.turn))   
        display_board(gamestate)
        return move_ops(gamestate)
    except ValueError:
        print('\n' + str(drop) + ' Not avalid column')
        move_drop(gamestate)
    except connectfour.ConnectFourGameOverError:
        print('Game Over')
        print('winner: ' + connectfour.winning_player(gamestate))
        return
    except connectfour.InvalidConnectFourMoveError:
        print('you can only pop your own peice')
        move_drop(gamestate)
示例#42
0
def conduct_connectfour_battle(user_host: str, user_port: int, user_id: str) -> None:
    the_winner = connectfour.NONE
    the_user = connectfour.RED
    try:
        s = connect_socket(user_host, user_port, user_id)
        setup_game(s)
        print('Connected! Let the Battle Begin!!!!!')
        game_state = connectfour.new_game_state()
        connectfour_consol.display_board(game_state.board)
        while the_winner == connectfour.NONE:
            if game_state.turn == the_user:
                print('%s this is your turn. Please make a move.' % user_id)
                move = int(input('where will you drop your piece? type 1~7.'))-1
            else:
                
        game_state = connectfour.drop_piece(game_state, move)
        display_board(game_state.board)
        the_winner = connectfour.winning_player(game_state)                
        
    except:
        print('Connection failed. Closing the game.')
    finally:
        s.close()
def auto_drop(gamestate, col):
    gamestate = gamestate._replace(board = connectfour.drop_piece(gamestate, int(col)).board,
                                              turn= connectfour._opposite_turn(gamestate.turn)) 
    return gamestate
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!')