def movement() -> str:
    ''' allows the player to pop or drop a disc into a given column
    and determines the winner'''

    gs = connectfour.new_game()
    connectfour_board.print_board(gs.board)
    print('If you want to drop type D, press enter and a column number.')
    print('If you want to pop type P, press enter and a column number.')
    while True:
        try:
            command = input()
            col = int(input())
            if command[0] == 'D':
                gs = connectfour.drop(gs, col - 1)
                connectfour_board.print_board(gs.board)
            else:
                gs = connectfour.pop(gs, col - 1)
                connectfour_board.print_board(gs.board)

            if connectfour.winner(gs) != connectfour.NONE:
                x = connectfour.winner(gs)
                if x == 1:
                    print('RED WINS!')
                elif x == 2:
                    print('YELLOW WINS!')

                return command + ' ' + col

        except ValueError:
            print('Try again')
            pass
Ejemplo n.º 2
0
def play_check(GS: connectfour.GameState, new_g: bool):
    '''passes in a GameState, checks to see if the user put drop or pop,
    if the user put drop, creates a drop namedtuple, and vice versa for pop,
    and then it updates the board, as well as printing it'''
    ## create a game movie so I can use the gamestate to update the board
    while True:
        if connectfour.winner(GS) == connectfour.NONE:
            command = input(
                "Would you like to pop, or drop. Enter 'DROP' or 'POP': "
            ).strip().upper()
            if command == 'DROP' or command == 'POP':
                num_col = choose_col()

                #fix the number based index
                #create a game_move namedtuple

                gNT = Move(command, num_col)  #print_player_turn(GS, new_g)
                GS = update_board(gNT, GS)
                break
        else:
            if connectfour.winner(GS) == connectfour.RED:
                print("You, Red, have won")
                break
            elif connectfour.winner(GS) == connectfour.YELLOW:
                print("I'm sorry, the server has won. You lose!")
                break

    return (GS, gNT)
Ejemplo n.º 3
0
def gameplay(game_state):
    while True:
        try:
            shared_functions.print_board(game_state)
            _user_input = shared_functions.user_input(game_state)
            game_state = shared_functions.drop_or_pop_action(
                game_state, _user_input)
        except IndexError:
            print("INVALID")
            continue
        except connectfour.InvalidMoveError:
            shared_functions.print_board(game_state)
            continue
        except connectfour.GameOverError:
            print("Game is already over")
            break
        except ValueError:
            shared_functions.print_board(game_state)
            continue
        except AttributeError:
            print('INVALID')
            continue
        if connectfour.winner(
                game_state) == connectfour.RED or connectfour.winner(
                    game_state) == connectfour.YELLOW:
            shared_functions.who_won(game_state)
            break

    print("End of game")
Ejemplo n.º 4
0
def console():
    '''This function runs the game from start to finish.
        It will first starta  new game, then while there is no winner, it will loop between
        the red player and the yellow player. Once there is a winner, it will print the winner and end the program.'''
    gamestate = connectfour_tools.gamestart()
    winner = connectfour.winner(gamestate)
    turn = connectfour_tools.turnchecker(gamestate)

    while winner == connectfour.NONE:
        if turn == connectfour.RED:
            print("Red player's turn.")
            column = connectfour_tools.columninput()
            move = connectfour_tools.moveinput()
            gamestate = movechecker(gamestate, column, move)
            connectfour_tools.gameboard(gamestate)
            winner = connectfour.winner(gamestate)
            turn = connectfour_tools.turnchecker(gamestate)

        elif turn == connectfour.YELLOW:
            print("Yellow player's turn.")
            column = connectfour_tools.columninput()
            move = connectfour_tools.moveinput()
            gamestate = movechecker(gamestate, column, move)
            connectfour_tools.gameboard(gamestate)
            winner = connectfour.winner(gamestate)
            turn = connectfour_tools.turnchecker(gamestate)

    if winner == connectfour.RED:
        print("Red player wins.")

    else:
        print("Yellow player wins.")
Ejemplo n.º 5
0
def gameplay():
    '''
    This function processes the entire game with the AI as well as the setting
    up of the game.
    '''
    try:
        connection_and_username = begin_game()
        connection = connection_and_username[0]
        username = connection_and_username[1]
    except InvalidServerError:
        return
    
    ai_gamestate = connectfour.new_game()
    while(connectfour.winner(ai_gamestate) == connectfour.NONE):
        try:
            ai_gamestate = _user_turn(ai_gamestate, connection, username)
            print()
        except connectfour_protocol.ConnectFourProtocolError:
            print('Invalid Input. Please Try Again.')
        except connectfour_protocol.InvalidServerMoveError:
            print('Invalid Input. Please Try Again.')
        except InvalidServerError:
            return

    connectfour_shared.print_board(ai_gamestate)
    print()
    
    if(connectfour.winner(ai_gamestate) == connectfour.RED):
        print('Congratulations! You have won the game!')
    else:
        print('Sorry. The AI has won the game.')

    connectfour_protocol.disconnect(connection)
Ejemplo n.º 6
0
def run_turn(game_state: connectfour.GameState) -> int:
    '''Runs a turn by first checking if there is a winner; otherwise the user
    is asked whether to drop or pop a piece'''

    #initialize value where there is no winner when starting a game
    winner = False

    while not winner:

        #checks whether the winning player is NONE from connectfour
        if connectfour.winner(game_state) == connectfour.NONE:

            print("It is currently Player " +
                  connectfour_modules.values_to_symbols(game_state.turn) +
                  "'s turn")

            game_state = drop_or_pop(game_state)

        #checks whether player R has won the game by comparing with RED from connectfour
        elif connectfour.winner(game_state) == connectfour.RED:
            print('RED player has won!')

            #winner has been declared, ending loop and the game
            winner = True

        #player Y wins the game if connectfour.winner is neither NONE nor RED
        else:
            print('YELLOW player has won!')
            winner = True
Ejemplo n.º 7
0
def WinningBanner(GameState, S1: str, S2: str) -> str:
    ''' Given the GameState and the names of the users, this function determines if there
    is a winner and prints a banner with the winner's name to end the program '''

    if connectfour.winner(
            GameState
    ) == 1:  # If Red wins then the winning banner for red is printed!
        time.sleep(1)
        Project2commonUI.delay_print(
            '\n**************************************\n')
        Project2commonUI.delay_print(
            ' Player RED -- {} has won! :D \n'.format(S1))
        Project2commonUI.delay_print(
            '**************************************\n')
        time.sleep(2)
        return 'You may exit the program!'  # Returns a string to indicate exiting the program

    elif connectfour.winner(GameState) == 2:
        time.sleep(1)
        Project2commonUI.delay_print(
            '\n**************************************\n'
        )  # If Yellow wins then the winning banner for yellow is printed!
        Project2commonUI.delay_print(
            ' Player YELLOW -- {} has won! :D \n'.format(S2))
        Project2commonUI.delay_print(
            '**************************************\n'
        )  # Returns a string to indicate exiting the program
        time.sleep(2)
        return 'You may exit the program!'
def online_gameplay(connection: connectfour_socket.GameConnect):
    '''Runs the Connect Four game on the user interface.'''
    game_state = connectfour.new_game()
    x = 0
    connectfour_gameplay.numbers(x)
    connectfour_gameplay.dot_rows(game_state)
    while True:
        x = connectfour_gameplay.name_turn(game_state)
        if x == connectfour.RED:
            game_state = red_turn(game_state, connection)
            connectfour_gameplay.numbers(x)
            connectfour_gameplay.dot_rows(game_state)
            x = connectfour.winner(game_state)
        elif x == connectfour.YELLOW:
            game_state = yellow_turn(game_state, connection)
            connectfour_gameplay.numbers(x)
            connectfour_gameplay.dot_rows(game_state)
            x = connectfour.winner(game_state)
        elif x == connectfour.NONE:
            print('hi')

        if x == connectfour.NONE:
            continue
        elif x == connectfour.RED:
            print('GAME OVER. The winner is red.')
            break
        elif x == connectfour.YELLOW:
            print('GAME OVER. The winner is yellow player.')
            break
        connectfour_gameplay.name_turn(game_state)
Ejemplo n.º 9
0
def _play_game(game_state: connectfour.GameState):
    ''' Tells the user the correct input format for the game,
    and starts playing the game with the server. It will also let
    the user know who is the winner when the game is over.
    '''
    print(
        'Welcome! In order to play the game, please type "DROP #" or \n'
        '"POP #" with # as the column that you want to drop or pop the piece!')
    print(c4_shared_function.board(game_state))

    while True:
        user_command = input()

        if c4_shared_function.game_move(game_state, user_command) is None:
            continue

        game_state = c4_shared_function.game_move(game_state, user_command)

        print(c4_shared_function.board(game_state))

        if connectfour.winner(game_state) == connectfour.RED:
            print('WINNER_RED')
            sys.exit()
        elif connectfour.winner(game_state) == connectfour.YELLOW:
            print('WINNER_YELLOW')
            sys.exit()
Ejemplo n.º 10
0
def run_game(position: 'GameState') -> 'GameState' or None:

    connectfour.winner(position)

    if connectfour.winner(position) == connectfour.NONE:
        theanswer = obtainanswer()
        if theanswer == 'D':
            column_num = overlimit(position)

            nextstep = connectfour.drop(position, column_num)
            board(nextstep)
            return run_game(nextstep)
        elif theanswer == 'P':
            column_num = int(input('Enter a column number from 1-7: ')) - 1
            try:
                nextstep = connectfour.pop(position, column_num)
            except:
                run_game(position)
            else:
                board(nextstep)
                return run_game(nextstep)


##            if nextstep == connectfour.InvalidMoveError():
##                run_game(position)
##            else:
##                board(nextstep)
##                return run_game(nextstep)

    else:
        thewinner = connectfour.winner(position)
        if thewinner == 1:
            print('Red wins!')
        elif thewinner == 2:
            print('Yellow wins!')
Ejemplo n.º 11
0
def start_game() -> None:
    """
    The main entry point for the program.
    Starts the console version of the connect four game.
    """
    print("Welcome to ICS 32 Connect Four!")
    gameState = connect.new_game()
    while connect.winner(gameState) == connect.NONE:
        lib.print_game_state(gameState)
        print('')
        lib.print_turn(gameState)
        while True:
            col, move = lib.prompt_and_get_move()
            try:
                gameState = lib.execute_move(gameState, col, move)
                break
            except connect.InvalidMoveError:
                if move == lib.POP_BOTTOM:
                    print('Can not pop on the given column')
                else:
                    print('Can not drop on the given column')
    winner = connect.winner(gameState)
    print()
    lib.print_game_state(gameState)
    print(lib.get_player_string(winner) + ' has won the game! Congrats!')
    return
Ejemplo n.º 12
0
def gameplay(game_state, game_connection) -> None:
    '''Main gameplay funtion. Ends the game/breaks out of loop if an error is found. '''
    
    while True:
        try:
            if game_state.turn == connectfour.RED:
                shared_functions.print_board(game_state)
                game_state = user_input(game_state, game_connection)
            elif game_state.turn == connectfour.YELLOW: 
                shared_functions.print_board(game_state)
                game_state = server_input(game_state, game_connection)

        except IndexError:   
            print('Game has ended with no winner')
            break
        except connectfour.InvalidMoveError:
            print('Game has ended with no winner')
            break
        except connectfour.GameOverError:
            print("Game is already over")
            break
        except ValueError:
            print('Game has ended with no winner')
            break
        except AttributeError:
            print('Game has ended with no winner')
            break

        if connectfour.winner(game_state)==connectfour.RED or connectfour.winner(game_state) == connectfour.YELLOW:
            shared_functions.print_board(game_state)
            shared_functions.who_won(game_state)
            break

    socket_handling.close(game_connection)
Ejemplo n.º 13
0
def run_user_interface() -> None:
    'Starts the console veresion of connectfour'
    game_state = connectfour.new_game()
    print("Columns should be selected by typing a number between 1 and 7")
    print("Specify a move in the format of DROP col# or POP col#")
    print("replace col# with the column's number that you want selected")
    turn = 0
    while (connectfour.winner(game_state) == connectfour.NONE):
        if turn % 2 == 0:
            print('______________________')
            print("PLAYER RED'S TURN")
        else:
            print('______________________')
            print("PLAYER YELLOW'S TURN")
        user_input = input('Enter a move: ')
        game_state = shared_functions.process_user_input(
            game_state, user_input)
        shared_functions.print_game_board(game_state)
        turn += 1
    winner = connectfour.winner(game_state)
    if winner == 1:
        winner_color = 'PLAYER RED'
    else:
        winner_color = 'PLAYER YELLOW'
    print('Congratulations ' + winner_color + ', you are the winner!')
Ejemplo n.º 14
0
def run_game(position: 'GameState') -> 'GameState' or None:

    connectfour.winner(position)

    if connectfour.winner(position) == connectfour.NONE:
        theanswer = local_tools.obtainanswer()
        if theanswer == 'D':
            column_num = local_tools.overlimit(position)

            nextstep = connectfour.drop(position, column_num)
            local_tools.board(nextstep)
            return run_game(nextstep)
        elif theanswer == 'P':
            column_num = int(input('Enter a column number from 1-7: ')) - 1
            try:
                nextstep = connectfour.pop(position, column_num)
            except:
                run_game(position)
            else:
                local_tools.board(nextstep)
                return run_game(nextstep)
    else:
        thewinner = connectfour.winner(position)
        if thewinner == 1:
            print('Red wins!')
        elif thewinner == 2:
            print('Yellow wins!')
Ejemplo n.º 15
0
def play_game_for_yellow(position: 'GameState', dorp: str,
                         col: str) -> 'GameState' or None:

    connectfour.winner(position)
    print(dorp + col)
    if connectfour.winner(position) == connectfour.NONE:
        if dorp == 'D':
            nextmove = connectfour.drop(position, col)
            board(nextmove)
            return play_game_for_red(nextmove, connection, connectionout)
        elif dorp == 'P':
            column_num = int(input('Enter a column number from 1-7: ')) - 1
            try:
                nextmove = connectfour.pop(position, column_num)
            except:
                play_game(position)
            else:
                board(nextmove)
                return play_game_for_red(nextmove, connection, connectionout)
    else:
        thewinner = connectfour.winner(position)
        if thewinner == 1:
            print('Red wins!')
        elif thewinner == 2:
            print('Yellow wins!')
Ejemplo n.º 16
0
def player_wins(game_state):
    """
    Executed when a players wins the game
    """
    if connectfour.winner(game_state) != 0:
        if connectfour.winner(game_state) == 1:
            print("Red Player Wins")
        elif connectfour.winner(game_state) == 2:
            print("Yellow Player Wins")
Ejemplo n.º 17
0
def check_if_winner(gamestate: ["board", "turn"]) -> None:  #called by main()
    """Check if there's a winner"""
    if connectfour.winner(gamestate) == connectfour.RED:
        print("RED wins")
        return True  #ends program if winner
    elif connectfour.winner(gamestate) == connectfour.YELLOW:
        print("YELLOW wins")
        return True  #ends program if winner
    else:
        return False  #continue program if no winner
Ejemplo n.º 18
0
def printWinner(gamestate: connectfour.GameState):
    """ Prints out the winner or tie if the game comes to an end"""

    if (connectfour.winner(gamestate) == 1):
        print("WINNER: RED")
    elif (connectfour.winner(gamestate) == 2):
        print("WINNER: YELLOW")
    else:
        print("TIE")
    print("Thanks for playing!")
Ejemplo n.º 19
0
def winner_banner(game_state: 'GameState'):
    "Prints a message if a player has won or else it does nothing."
    if connectfour.winner(game_state) == connectfour.RED:
        print("The game is over. Red player won!")
        pass
    elif connectfour.winner(game_state) == connectfour.YELLOW:
        print("The game is over. Yellow player won!")
        pass
    else:
        pass
Ejemplo n.º 20
0
def printWinner(gamestate: connectfour.GameState):
	""" Prints out the winner or tie if the game comes to an end"""

	if (connectfour.winner(gamestate) == 1):
		print("WINNER: RED")
	elif (connectfour.winner(gamestate) == 2):
		print("WINNER: YELLOW")
	else:
		print("TIE")
	print("Thanks for playing!")
Ejemplo n.º 21
0
def winner_print(gamestate: connectfour.GameState) -> str:
    ''' prints out winner when one is given '''
    statement = 'No Winner'

    if connectfour.winner(gamestate) == 1:
        statement = "RED player has WON"
    elif connectfour.winner(gamestate) == 2:
        statement = "YELLOW player has WON"

    return statement
Ejemplo n.º 22
0
def winner(game) -> bool:
       if connectfour.winner(game) == connectfour.RED:
              print('Red is the winner')
              return True
       
       elif connectfour.winner(game) == connectfour.YELLOW:
              print("Yellow is the winner")
              return True
       else:
              return False       
def playConnectFour():
    GameState = connectfour.new_game()  #changed to game state
    while connectfour.winner(GameState) == 0:  #changed to game state
        GameState = connectfour_functions.playerMove(
            GameState)  #both changed to gamestate
        connectfour_functions.displayBoard(GameState)  #changed to game state
    if connectfour.winner(GameState) == 1:
        print("RED player wins!")
    elif connectfour.winner(GameState) == 2:
        print("YELLOW player wins!")
Ejemplo n.º 24
0
def check_winner(current_gamestate) -> bool:
    """Returns True or False depending on if a winner is decided"""
    if connectfour.winner(current_gamestate) == 1:
        print("\nRED PLAYER IS THE WINNER!")
        return True
    elif connectfour.winner(current_gamestate) == 2:
        print("\nYELLOW PLAYER IS THE WINNER!")
        return True
    else:
        None
def start_game() -> None:
    """
    The main entry point for the program.
    Starts the networked version of the connect four game.
    """
    print("Welcome to ICS 32 Connect Four!")
    host, port = get_address_and_port()
    username = get_username()

    if not network.connect_to_game_server(host, port, username):
        print('A connection could not be established with the server')
        return

    print('Successfully connected to the server. Ready to begin the game.')
    print('')
    gameState = connectfour.new_game()

    while connectfour.winner(gameState) == connectfour.NONE:
        if gameState.turn == connectfour.RED:
            lib.print_game_state(gameState)
            print('')
            print('You are the Red player. It is your move.')
            while True:
                col, move = lib.prompt_and_get_move()
                response = network.send_move(move, col)
                if response == network.TERMINATED:
                    connection_terminated()
                    return
                elif response == network.ILLEGAL:
                    print("Invalid move. Try again.")
                else:
                    gameState = lib.execute_move(gameState, col, move)
                    break

        else:
            lib.print_game_state(gameState)
            print('')
            move, col = network.receive_move()
            if move == network.TERMINATED:
                connection_terminated()
                return
            gameState = lib.execute_move(gameState, col, move)
            print('The Yellow player has made the move: ' + move + ' ' +
                  str(col))

    winner = connectfour.winner(gameState)
    print()
    lib.print_game_state(gameState)
    print('')
    if winner == connectfour.RED:
        print('You have won the game! Congrats!')
    else:
        print('The Yellow player has won the game.')
    network.terminate_connection()
    return
Ejemplo n.º 26
0
def check_winner(game_state: 'GameState') -> bool:
    '''Return if someone has won and print the result'''
    if connectfour.winner(game_state) == connectfour.RED:
        connectfour_shared_ui.print_board(game_state)
        print('RED is the winner!')
        return True
    elif connectfour.winner(game_state) == connectfour.YELLOW:
        connectfour_shared_ui.print_board(game_state)
        print('YELLOW is the winner!')
        return True
    return False
Ejemplo n.º 27
0
def main():
    game = connectfour.new_game()
    while True:
        game = input_move(game)
        connectfour_tools.print_game(game)
        if connectfour.winner(game) == connectfour.RED:
            print("RED wins! Congratulations!")
            break
        elif connectfour.winner(game) == connectfour.YELLOW:
            print("YELLOW wins! Congratulations!")
            break
def print_winner(game_state: connectfour.GameState):
    '''checks if there is a winner of the game yet and prints who it is if there is.'''
    if connectfour.winner(game_state)==0:
        return
            
    elif connectfour.winner(game_state)==1:
        print('WINNER: RED')
        return
                   
    elif connectfour.winner(game_state)==2:
        print('WINNER: YELLOW')
        return 
Ejemplo n.º 29
0
def startgame() -> None:
	game_state = connectfour.new_game()
	connectfour_game.print_board(game_state)
	while connectfour.winner(game_state) == 0:
		connectfour_game.print_turn(game_state)
		move = connectfour_game.drop_or_pop()
		column_number = connectfour_game.ask_column()
		game_state = connectfour_game.game_progress(game_state,move,column_number)
		connectfour_game.print_board(game_state)
	if connectfour.winner(game_state) == 1:
		print('RED WINS!')
	elif connectfour.winner(game_state) == 2:
		print('YELLOW WINS!')
Ejemplo n.º 30
0
def _start_game(connection: connectfour_socket.ConnectfourConnection) -> None:
    game_state = connectfour.new_game()
    connectfour_game.print_board(game_state)
    while connectfour.winner(game_state) == 0:
        if connectfour_socket.AI_ready(connection):
            connectfour_game.print_turn(game_state)
            game_state, response = _player_turn(connection, game_state)
            if response == 'OKAY':
                connectfour_game.print_turn(game_state)
                game_state = _AI_turn(connection, game_state)
    if connectfour.winner(game_state) == 1:
        print('RED wins!')
    elif connectfour.winner(game_state) == 2:
        print('YELLOW wins!')
Ejemplo n.º 31
0
def continue_game(game_state: connectfour.GameState):
    winner = connectfour.winner(game_state)
    while winner == connectfour.NONE:
        try:
            player_input = cf.ask_for_cmd()
            game_state = cf.take_action_on_command(player_input, game_state)
            cf.print_board(game_state)
            winner = connectfour.winner(game_state)
            _determine_winner(winner)
        except connectfour.InvalidMoveError:
            print("Invalid move. Please try again.")
        except connectfour.GameOverError:
            print("You cannot make any additional moves. The game has ended.")
        except ValueError:
            print("Invalid column. Please try again.")
Ejemplo n.º 32
0
def run_program() -> None:
    '''runs the user interface'''
    currentState = connectfour.new_game()
    print(
        'Welcome to Connect Four! Type DROP or POP then the column number to begin.'
    )
    while (connectfour.winner(currentState) == connectfour.NONE):
        action = input()
        currentState = handle_drop_pop(currentState, action)
        print_game_state(currentState)
        #print(currentState.board)
    if (connectfour.winner(currentState) == 1):
        print('Red won!')
    if (connectfour.winner(currentState) == 2):
        print('Yellow won!')
Ejemplo n.º 33
0
def start_game(connection: connect_four_protocol.connection) -> None:
    ''' start the game and handle the move made by the players '''            
    game = connectfour.new_game()
    connectfour.print_game_board(game)

    while True:
        my_connectfour.print_game_board(game)
        
        if(game.turn == 1):
            print("Player Red Turn")
        elif(game.turn == 2):
            print("Player Yellow Turn")
        print()

        column = my_connectfour.get_column()
        move  = my_connectfour.select_move()
        
        game = my_connectfour.handle_move(game,column, move)
        
        my_connectfour.winner = connectfour.winner(game)

        if my_connectfour.winner != connectfour.NONE:

            
            my_connectfour.print_game_board(game)
            my_connectfour.game_over()
            break
Ejemplo n.º 34
0
def winner_is_chosen(game_state):
    ''' Checks if the game board has a winner in it'''
    winner = connectfour.winner(game_state)
    if winner == connectfour.NONE:
        return winner
    else:
        return winner
Ejemplo n.º 35
0
def checkWin(gamestate: connectfour.GameState):
	"""Checks the current gamestate to see if anybody has won and accordingly return the boolean to
	state the current game situtation"""

	if (connectfour.winner(gamestate) == 0):
		return True
	return False
def run_game() -> None:
    ''' Starts a local game '''
    utils.print_instructions()
    game_state = game.new_game()
    
    winner = game.NONE
    players = ("RED", "YELLOW")
    yellow_turn =  False
    
    while winner == game.NONE:
        utils.print_board(game_state.board)
        player_move = utils.get_input(game_state,players[yellow_turn])
        
        # Select a player action 
        try:
            game_state = utils.execute_move(game_state,player_move)
        except game.InvalidMoveError:
            print("[Connect Four] Invalid move")
            continue

        # Swap players
        yellow_turn = not yellow_turn

        winner = game.winner(game_state)

    utils.print_board(game_state.board)

    winner_name = 'NONE'
    if winner == game.RED:
        winner_name = 'RED'
    elif winner == game.YELLOW:
        winner_name = 'YELLOW'

    print('[Connect Four] Winner: {}'.format(winner_name))
Ejemplo n.º 37
0
def start_game(connection: connect_four_protocol.Connection,) -> None:
    ''' start the game and handle the move made by the players '''
    
    _game = connectfour.new_game()
    my_connectfour.print_game_board(_game)
    _game = client_turn(connection, _game)
    while True:
                
        winner = connectfour.winner(_game)
        if winner == 1:
            my_connectfour.print_game_board(_game)
            print('You (Red Player) won')
            break
        elif winner == 2:
            print('Player Yellow won')
            break
        else:
            my_connectfour.print_game_board(_game)
 
        AI_message = connect_four_protocol.recv_message(connection)

        if AI_message  == "OKAY":
            _new_game = server_turn(connection,_game)
            
            _game = _new_game
            my_connectfour.print_game_board(_game)

        AI_message = connect_four_protocol.recv_message(connection)

        if AI_message == "READY":
            print("Player red's turn ")
            _game = client_turn(connection, _game)
            print()
Ejemplo n.º 38
0
def user_interface()->None:
    ''' main part of the program that controls the game functionality'''
    print("Welcome to ConnectFour Game...\n")

    game =  connectfour.new_game()
    
    while True:
        my_connectfour.print_game_board(game)
        
        if(game.turn == 1):
            print("Player Red Turn")
        elif(game.turn == 2):
            print("Player Yellow Turn")

        column = my_connectfour.get_column()
        move  = my_connectfour.select_move()
        game = my_connectfour.handle_move(game,column, move)
        
        my_connectfour.winner = connectfour.winner(game)

        if my_connectfour.winner != 0:

            my_connectfour.print_game_board(game)
            my_connectfour.game_over(my_connectfour.winner)
            break
def main() -> None:
    # Connect to server
    while True:                 
        connection = net_utils.connect_to_server()
        if connection != None:
            user = net_utils.get_username()
            if net_utils.start_game(connection, user):                
                break
            else:
                return

    # Test code
    #connection = net_utils._open_connection("woodhouse.ics.uci.edu", 4444)
    #user = "******"
    #net_utils.start_game(connection, user)
    #random.seed(calendar.timegm(time.gmtime()))
    
    # Variable Initialization
    winner = game.NONE
    players = ("RED", "YELLOW")
    player_names = {"RED": user, "YELLOW": "Server AI"}
    server_turn = False
    player_move = None

    input_format = "[{{}}] {}:".format(user)
    utils.print_instructions()
    game_state = game.new_game()

    while winner == game.NONE:
        utils.print_board(game_state.board)

        # Receive player moves and execute server side
        if not server_turn:
            # Test bot code
            #player_move = get_random_move()
            player_move = utils.get_input(game_state,players[server_turn], input_format)
        else:
            player_move = net_utils.sync_move(connection, player_move.action, player_move.col)
            print('[{}] {}: {} {}'.format(players[server_turn], \
                                          player_names[players[server_turn]], \
                                          player_move.action.title(), \
                                          (player_move.col + 1)))

        # Execute player moves
        try:
            game_state = utils.execute_move(game_state,player_move)
            winner = game.winner(game_state)
        except game.InvalidMoveError:
            print("[Connect Four] Invalid move")
            continue

        server_turn = not server_turn

    # Sync final moves to server and validate
    #  the winner remotely and locally
    player_move = net_utils.sync_move(connection, player_move.action, player_move.col)
    utils.print_board(game_state.board)
    _validate_winner(players[winner-1],player_move.winner,player_names)

    net_utils.end_game(connection)
Ejemplo n.º 40
0
def WinningBanner(GameState, S1: str, S2: str) -> str:
    ''' Given the GameState and the names of the users, this function determines if there
    is a winner and prints a banner with the winner's name to end the program '''
    
    if connectfour.winner(GameState) == 1:                                                # If Red wins then the winning banner for red is printed!
        time.sleep(1)
        Project2commonUI.delay_print('\n**************************************\n')
        Project2commonUI.delay_print(' Player RED -- {} has won! :D \n'.format(S1))
        Project2commonUI.delay_print('**************************************\n')
        time.sleep(2)
        return 'You may exit the program!'                                                # Returns a string to indicate exiting the program

    elif connectfour.winner(GameState) == 2:
        time.sleep(1)
        Project2commonUI.delay_print('\n**************************************\n')        # If Yellow wins then the winning banner for yellow is printed!
        Project2commonUI.delay_print(' Player YELLOW -- {} has won! :D \n'.format(S2))
        Project2commonUI.delay_print('**************************************\n')          # Returns a string to indicate exiting the program
        time.sleep(2)
        return 'You may exit the program!'
Ejemplo n.º 41
0
def program(game):
    """
    program that handles the connect four game
    """
    while connectfour.winner(game) == 0:  # while there is no winner
        if game.turn == 1:  # if it is red player's turn
            print("Player RED make your move")  # prints this message
            print()
        elif game.turn == 2:  # if it is yellow players turn
            print("Player YELLOW make your move")  # prints this message
            print()
        sharedfunctions.print_board(game.board)  # print a new game
        current_move = sharedfunctions.get_move()  # gets the players move and stores it in a variable

        while True:

            try:

                if current_move[0].upper() == "DROP":  # if players says they want to drop
                    game = connectfour.drop(
                        game, int(current_move[-1]) - 1
                    )  # drops the players move in appropriate column and changes the game state
                elif current_move[0].upper() == "POP":  # if player says they want to pop
                    game = connectfour.pop(
                        game, int(current_move[-1]) - 1
                    )  # pops players move as long as players piece is in specified column

            except:
                print("Invalid Move")  # if playes move is invalid prints this message
                print()
                current_move = sharedfunctions.get_move()  # recursively ask for players move until input is acceptable
            else:
                break  # leave the function
        print("\n\n")
    sharedfunctions.print_board(game.board)  # prints new game state
    print("Game Over")  # when game is over prints this message
    if game.turn == 1:  # if it is red playes turn
        print("Player YELLOW is the Winner")  # print this message
    elif game.turn == 2:  # if is is yellow players turn
        print("Player RED is the Winner")  # print this message
Ejemplo n.º 42
0
def winner_is_chosen(game_state):
    winner = connectfour.winner(game_state)
    if winner == connectfour.NONE:
        return winner
    else:
        return winner
Ejemplo n.º 43
0
def main_program(game):
    '''
    program that handles the connect four game
    '''
    try:
        
        x = random() #(prompts user for a username, host and port. this is the first function in this module
        c = connecting.connection(x.host, x.port) #connects to given host and port
        connecting.send_move(c, 'I32CFSP_HELLO ' + x.username) #send a message and includes the username provided by user
        connecting.read_line(c) #reads a line from the server
        connecting.send_move(c, 'AI_GAME') #sends this message to the server
        connecting.read_line(c) #reads a line from the server
        
        while connectfour.winner(game) == 0: #while there is no winner

            if game.turn == 1: #if it is player 
                print('Player RED make your move') #prints this message
                print()


                sharedfunctions.print_board(game.board) #print a new game


                while True:

                    try:
                        current_move = sharedfunctions.get_move() #gets the players move and stores it in a variable
                        print('\n')
                        
                        if current_move[0].upper().startswith('DROP'): #takes players input at first index, makes it uppercase and checks if it equals a string
                            current_move = int(current_move[-1]) #converts players move at last index to an integer
                            current_move = current_move - 1 #subtracts 1 from players move to account for indexing
                            game = connectfour.drop(game, current_move) #calls drop function from connectfour module that handles dropping a piece onto connect four board
                            sharedfunctions.print_board(game.board) #prints updated game board
                            connecting.send_move(c, 'DROP ' + str(current_move+1)) #sends string and adds one to players move to account for subtractoin earlier then converts players move back to a string to send to the server
                            break #leaves the function
              


                        elif current_move[0].upper().startswith('POP'): #takes players input at first index, makes it uppercase and checks if it equals a string
                            current_move = int(current_move[-1]) #converts players move at last index to an integer
                            current_move = current_move - 1 #subtracts 1 from players move to account for indexing
                            game = connectfour.pop(game, current_move) #calls pop function from connectfour module that handles popping a piece onto connect four board
                            sharedfunctions.print_board(game.board) #prints updated game board
                            connecting.send_move(c, 'POP ' + str(current_move+1)) #sends string and adds one to players move to account for subtractoin earlier then converts players move back to a string to send to the server
                            break #leaves the function

                    except:
                        print('Invalid Move') #prints this message if try statement fails
                        print()
            
                    
                
            elif game.turn == 2: #if it is the servers move

                connecting.read_line(c) #read input from server
                servers_move = connecting.read_line(c) #reads another line from server. this is servers move

                if servers_move.startswith('POP'): #if servers move starts with POP
                    servers_move = int(servers_move.split()[-1]) #split servers input and grab last index and convert to an integer
                    servers_move = servers_move - 1 #subtracts one from servers move to account for 0 indexing
                    connecting.read_line(c) #read line of input from server
                    game = connectfour.pop(game, servers_move) #calls pop function from connectfour module that handles popping a piece onto connect four board
                    sharedfunctions.print_board(game.board) #prints updated game board

                else:
                    servers_move = int(servers_move.split()[-1]) #split servers input and grab last index and convert to an integer
                    servers_move = servers_move - 1 #subtracts one from servers move to account for 0 indexing
                    connecting.read_line(c) #read line of input from server
                    game = connectfour.drop(game, servers_move) #calls drop function from connectfour module that handles dropping a piece onto connect four board
                    sharedfunctions.print_board(game.board) #prints updated game board


            print('\n\n')
        sharedfunctions.print_board(game.board) #prints new game state
        print('Game Over') #when the game is over prints this message
        if game.turn == 1: #if it is red players turn (player red has lost)
            print('Sorry, you have lost') #prints this message
        elif game.turn == 2: #if it yellow players move (player yellow has lost)
            print('Congratulations! You have won') #prints this message
    except:
        print('The connection was unsuccessful')

    finally:

        try:
            connecting.close(c) #closes the connection

        except:
            print('Goodbye')
Ejemplo n.º 44
0
# SHAMBHU THAPA 10677794  , DANIEL RAMIREZ 57298305
import connectfour

_game = connectfour.new_game() 
game_winner  = connectfour.winner(_game)

def print_game_board(_game: 'connectfour.ConnectFourGameState') -> None:
    ''' Displays the game state as the game is running '''

    print()
    for i in range(connectfour.BOARD_COLUMNS):
        print(i+1, end = ' ')
    print()

    for row in range(connectfour.BOARD_ROWS):
        for col in range(connectfour.BOARD_COLUMNS):
            if _game.board[col][row] == connectfour.NONE:
                print('.', end = ' ')
            elif _game.board[col][row] == connectfour.RED:
                 print('R', end=' ')
            elif _game.board[col][row] == connectfour.YELLOW:
                 print('Y', end=' ') 
            else:
                print(_game.board[col][row], end =' ')
        print()
    print()

def get_column() ->int:
    ''' prompt the user to choose a desired column'''