Exemplo n.º 1
0
def run_network_connectfour():
    ''' Initiates the ConnectFour program that connects to a server
    '''
    Connection = _valid_connection()

    if Connection != None:

        Username = connectfour_server_protocol.username()

        connectfour_server_protocol.hello(Connection, Username)

        connectfour_server_protocol.request(Connection, 'AI_GAME')

        print()
        print('Welcome to ConnectFour!')
        print()
        print('Let\'s begin!')

        gameBoard = connectfour.new_game()

        connectfour_server_protocol.networkGame(Connection, gameBoard)

        connectfour_server_protocol.close(Connection)

    else:
        print('Closing program.')
Exemplo n.º 2
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
Exemplo n.º 3
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!')
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)
def execute_game(connection: 'connection'):
	'''Execution block of the network version of Connect Four game. 
	Takes turns between user and server until server detects a winner.'''
	game_state = connectfour.new_game()
	connectfour_functions.print_board(game_state)
	print()
	winner = connectfour.NONE
	server_response = ''

	while (winner == connectfour.NONE):
		game_over = check_game_over(server_response)
		if game_over == True:
			break
		if game_state.turn == connectfour.RED:
			print('It is Red Player\'s turn')
			game_state = user(connection, game_state)
			server_response = connectfour_network.receive_response(connection)
		if game_state.turn == connectfour.YELLOW:
			while server_response != 'OKAY':
				server_response = connectfour_network.receive_response(connection)
			print('It is Yellow Player\'s turn')
			game_state = server(connection, game_state)
			server_response = connectfour_network.receive_response(connection) #OKAY or READY

		connectfour_functions.print_board(game_state)
Exemplo n.º 6
0
def main_game() -> None:
    '''Show user interface to the players'''

    _show_welcome_banner()

    game_state = connectfour.new_game()

    while True:
        common_functions.show_board(game_state)

        if _player_turns(game_state) == 1:
            print("It's RED turn.")
        elif _player_turns(game_state) == 2:
            print("It's YELLOW turn.")

        print()
        column_num = common_functions.choose_column()
        action = common_functions.choose_action()
        game_state = common_functions.make_action(game_state, column_num,
                                                  action)

        winner = connectfour.winner(game_state)

        if winner != connectfour.NONE:
            common_functions.show_board(game_state)
            common_functions.stop_game(winner)

            break
Exemplo n.º 7
0
def main_game(connection: I32CFSP.Connectfourconnection) -> None:
    '''Show user interface to the player'''
    game_state = connectfour.new_game()
    common_functions.show_board(game_state)
    return_message = I32CFSP.read_line(connection)
    while True:
        
        if return_message == 'READY':
            print("It's RED(You)'s turn")
            print()
            game_state = _player_turns(connection, game_state)
            common_functions.show_board(game_state)
            return_message = I32CFSP.read_line(connection)

        elif return_message == 'INVALID':
            return_message = I32CFSP.read_line(connection)
        
        elif return_message == 'OKAY':
            game_state = _AI_turns(connection, game_state)
            common_functions.show_board(game_state)
            return_message = I32CFSP.read_line(connection)

        elif return_message == 'WINNER_RED':
            common_functions.stop_game(connectfour.RED)
            break
        elif return_message == 'WINNER_YELLOW':
            common_functions.stop_game(connectfour.YELLOW)
            break
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)
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
Exemplo n.º 10
0
def start_game()->connectfour.GameState:
    '''
    creates new game and displays a blank board
    '''
    game = connectfour.new_game()
    display_board(game)
    return game
Exemplo n.º 11
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()
Exemplo n.º 12
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
Exemplo n.º 13
0
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)
Exemplo n.º 14
0
def run_user_interface() -> None:
    '''Runs the user interface and maintains the game until end.'''
    host = socketHandling.input_host()
    port = socketHandling.input_port()

    print('Connecting to {} (port {})...'.format(host, port))
    connection = socketHandling.connect(host, port)
    print('Connection successful.')
    name = socketHandling.input_username()

    is_connected = socketHandling.initial_protocol(connection, name)

    if is_connected != False:
        overlappingFunctions.print_welcome_message()
        gstate = connectfour.new_game()
        overlappingFunctions.display_board(gstate)

    while is_connected != False and connectfour.winner(
            gstate) == connectfour.NONE:
        if gstate.turn == connectfour.RED:
            GamePlusMove = overlappingFunctions.execute_move(gstate)
            socketHandling.send_message(connection, GamePlusMove.move)
            gstate = GamePlusMove.GameState
            overlappingFunctions.display_board(gstate)
        elif gstate.turn == connectfour.YELLOW:
            response = socketHandling.receive_response(connection)
            gstate = interpret_response(connection, response, gstate)
            overlappingFunctions.display_board(gstate)

    if is_connected != False:
        overlappingFunctions.print_winner(gstate)
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))
Exemplo n.º 16
0
def _gameloop() -> None:
    game_state = connectfour.new_game()
    
    connection = protocol.connect('woodhouse.ics.uci.edu', 4444)
    protocol.ready_game(connection)

    while True:
        
        common.display_game_board(game_state.board)

        if game_state.turn == connectfour.RED:
            try:
                game_state = _handle_red(game_state, connection)

            except:
                common.print_general_err()
                continue

        elif game_state.turn == connectfour.YELLOW:

            try:
                game_state = _handle_yellow(game_state, connection)

            except:
                print('The server returned an invalid move, closing connection')
                protocol.close(connection)
                break
                

        response = protocol.get_response(connection)
        if _handle_server_responses(response):
            common.display_game_board(game_state.board)
            protocol.close(connection)
            break
Exemplo n.º 17
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
Exemplo n.º 18
0
def main():
    connection = net_tools.connect()
    user = input("please input a username: "******"I32CFSP_HELLO " + user)
    check_input(connection, "WELCOME " + user)
    net_tools.send_output(connection, "AI_GAME")
    #check_input(connection,"READY")

    game = connectfour.new_game()
    while True:
        response = net_tools.receive_input(connection)
        if response == "READY":
            move = user_input(connection)
            response = net_tools.receive_input(connection)
            if response == "OKAY":
                game = user_move(game, move)
                connectfour_tools.print_game(game)
                game = server_move(game, connection)
                connectfour_tools.print_game(game)
            elif response == "INVALID":
                print("Invalid move")
            elif response == "WINNER_RED":
                break
            else:
                print('Sorry! something went wrong with the server.')
                net_tools.close_connection(connection)
        elif response == "WINNER_YELLOW":
            break
        else:
            print('Sorry! something went wrong with the server.')
            net_tools.close_connection(connection)
    print(response)
    connectfour_tools.print_game(game)
    net_tools.close_connection(connection)
Exemplo n.º 19
0
def connect_four_consoleUI():
    ''' This is the main user interface where the program is executed and the Connect Four
    game runs with all its respective functions '''
    
    WelcomeBanner()  # prints welcome banner
    print()
    PlayerRed = InputRed()       # creates player 1 - red
    PlayerYellow = InputYellow() # creates player 2 - yellow
    print()
    
    GameState = connectfour.new_game()            # starts a new game and prints an empty board
    Project2commonUI.printBoard(GameState.board)
    
    while True:
        PlayerTurn(GameState, PlayerRed, PlayerYellow)      # function call to PlayerTurn() which determines whose turn it is
        message = input()
        message = message.upper()                           # prompts for input to drop/pop a piece
            
        try:
            if len(message) == 0:                               # if there is nothing, this error is printed.
                print('\nSorry invalid input. Try again. :p\n')
            else:
                Responses = message.split()                     # otherwise the move is placed on the board and printed through InputMove()
                GameState = InputMove(Responses, GameState)
                
        except connectfour.InvalidMoveError:
            print('Invalid move! Try again. :p\n[ You can only POP your own piece or DROP a piece in an empty column! ]')  # error for invalid move
            
        except ValueError:
            print('Invalid column number! Try again. :p\n[ Number must be 1, 2, 3, 4, 5, 6, or 7! ]\n')         # error for value error - wrong col num.

        finally:
            Finale = WinningBanner(GameState, PlayerRed, PlayerYellow)        # prints the banner and returns the exit string
            if Finale == 'You may exit the program!':                         # if exit string is correct then the program breaks and ends.
                break       
Exemplo n.º 20
0
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))
Exemplo n.º 21
0
def main():
    overlap.welcome_banner()
    overlap.explain_rules()
    gamestate = connectfour.new_game()
    while True:
        overlap.display_current_board(gamestate)
        overlap.print_whose_turn(gamestate)
        gamestate = run_turn(gamestate)
Exemplo n.º 22
0
def console_user_interface() -> None:
    '''Runs console user interface'''
    print('Welcome to Connect-Four!')
    print('One player will use Red pieces designated by R \n' +
          'while another player will use Yellow pieces designated by Y')
    new_GameState = connectfour.new_game()
    print('Here is the starting game board: \n')
    connectfour_modules.display_game_board(new_GameState.board)
    run_turn(new_GameState)
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!")
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
Exemplo n.º 25
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 run_user_interface() -> None:
    '''Runs the user interface and maintains the game until end.'''
    overlappingFunctions.print_welcome_message()
    game_state = connectfour.new_game()
    overlappingFunctions.display_board(game_state)

    while connectfour.winner(game_state) == connectfour.NONE:
        GamePlusMove = overlappingFunctions.execute_move(game_state)
        game_state = GamePlusMove.GameState
        overlappingFunctions.display_board(game_state)
    else:
        overlappingFunctions.print_winner(game_state)
Exemplo n.º 27
0
def initializeGame():
	'''Begins the game by asking for the host,port, and username and finally creates a new GameState with the new connection'''

	while True:
		host = _prompt_For_Host()
		port = _prompt_For_Port()
		try:
			connection = lab2_socket.connect(host, port)
			break
		except:
			print("The connection could not be made. Please try again.")
	lab2_socket.hello(connection, _prompt_For_Username())
	playGame(connection, connectfour.new_game())
Exemplo n.º 28
0
def initializeGame():
    '''Begins the game by asking for the host,port, and username and finally creates a new GameState with the new connection'''

    while True:
        host = _prompt_For_Host()
        port = _prompt_For_Port()
        try:
            connection = lab2_socket.connect(host, port)
            break
        except:
            print("The connection could not be made. Please try again.")
    lab2_socket.hello(connection, _prompt_For_Username())
    playGame(connection, connectfour.new_game())
Exemplo 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!')
Exemplo n.º 30
0
def start_game(new_g: bool):
    ''' start the game'''
    print("\nWe are going to play Connect Four.\nRed always goes first.")

    #makes our gameboard, starts with all empty
    GS = connectfour.new_game()

    #prints player turn
    print_player_turn(GS, new_g)

    #prints the empty board
    print_screen(GS)
    return GS
Exemplo n.º 31
0
def _run_interface():
    game_state = connectfour.new_game()
    while True:
        cf_functions.print_board(game_state)
        gs_dp_col = cf_functions.move(game_state)
        game_state = gs_dp_col[0]
        win = connectfour.winner(game_state)
        if win == connectfour.RED:
            print('Player R has won the game.')
            break
        elif win == connectfour.YELLOW:
            print('Player Y has won the game.')
            break
Exemplo n.º 32
0
def run():
    '''runs game against the server using hidden functions'''

    try:
        host = input('Enter host: ')
        port = input('Enter port: ')
        connected = serverlogic.connect(host, int(port))
        game_state = connectfour.new_game()
        username = serverlogic.get_username()
        serverlogic.login(connected, username)
        serverlogic.send(connected)

    except:
        print("--Invalid Input--")

    else:

        while connectfour.winner(game_state) == connectfour.NONE:

            try:
                print()
                print("Turn:RED")
                print()
                popdrop, column_number = C4BG.userinput()
                print()
                game_state = C4BG.change_board(game_state, popdrop,
                                               column_number)
            except:
                print("Please re-enter")

            else:
                print('-------------------')
                print()
                print("Yellow's turn")
                print()
                print("Server Response:")
                to_server = popdrop.upper() + ' ' + str(column_number)
                serv_response = serverlogic.server_popdrop(
                    connected, to_server)
                print()
                if serv_response == 'WINNER_RED':
                    serverlogic.closeconnection(connected)
                    break
                if serv_response == 'WINNER_YELLOW':
                    serverlogic.closeconnection(connected)
                    break
                if serv_response != 'READY':
                    server_drop = serv_response.split()[0]
                    server_column = serv_response.split()[1]
                    game_state = C4BG.change_board(game_state, server_drop,
                                                   server_column)
Exemplo n.º 33
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!')
Exemplo n.º 34
0
def game(connection: 'connection') -> None:
    '''goes through server version of connect four'''
    intromessage(connection)
    print('Welcome to Connect 4!')
    print('You are the RED player!')
    gamestate = connectfour.new_game()
    connectfour_common.print_game_board(gamestate.board)
    connectfour_network.send_message(connection, ('AI_GAME'))

    while True:
        a = connectfour_network.read_message(connection)
        if (a) == 'READY':
            print('\nIt is the', connectfour_common.getturn(gamestate),
                  'players turn!')
            answer = input(
                'Choose if you want to DROP or POP and a column between 1 and '
                + str(connectfour.BOARD_COLUMNS) + '. (Ex. DROP 4)"\n')
            answer = isvalid(answer)
            anslist = answer.split()
            connectfour_network.send_message(connection, answer)
            try:
                c = (int(anslist[1]) - 1)
                gamestate = connectfour_common.doingmove(
                    anslist[0], c, gamestate)
                connectfour_common.print_game_board(gamestate.board)
            except:
                pass
        elif a == 'OKAY':
            print('\nIt is the', connectfour_common.getturn(gamestate),
                  'players turn!\n')
            output = connectfour_network.read_message(connection)
            move = printturn(output, gamestate, connection)
            col = (int(move[1]) - 1)
            gamestate = connectfour_common.doingmove(move[0], col, gamestate)
            connectfour_common.print_game_board(gamestate.board)
        elif a == 'INVALID':
            print('Invalid choice choose again.')

        elif a == "WINNER_RED":
            print('GAME OVER! You are the winner!')
            connectfour_network.close(connection)
            break

        elif a == "WINNER_YELLOW":
            print('GAME OVER! YOU LOST! Yellow player is the winner!')
            connectfour_network.close(connection)
            break
        elif a == ('ERROR'):
            print('Invalid choice choose again')
            pass
Exemplo n.º 35
0
def game():
    '''plays the game'''
    gameboard = connectfour.new_game()
    connectfour_opp.display_board(gameboard)
    while True:
        try:
            gameboard = connectfour_opp.move_user_red(gameboard)[0]
            connectfour_opp.display_board(gameboard)
            print()
            gameboard = connectfour_opp.move_user_yellow(gameboard)
            connectfour_opp.display_board(gameboard)
            print()
        except:
            break
def _begin_game() -> connectfour.GameState:
    '''
    This program begins the console game of Connect Four. It starts with a
    greeting and a brief summary of directions in order to play the game.
    The function ends by returning a board of a new game.
    '''
    print('Welcome to Connect Four!', end='\n\n')
    print(
        'Please enter the action you want to take. The two actions avaliable' +
        ' are DROP and POP. DROP is to place a disc in a specified column and'
        + ' POP is to take out your own disc at a specified column.\n')

    board_game = connectfour.new_game()
    return board_game
Exemplo n.º 37
0
def each_turn() -> None:
       '''
       Simulates turn for each player, updates gamestate, displays the
       board for the user to see and shows whose turn it is. Breaks and
       Displays the winner when the game is won.
       
       '''
       game = connectfour.new_game()


       while True:
              common.display_turn(game)
              player_move = common.interpret_user_input()
              
              if player_move.Action == 'D':
                     try:
                            game = connectfour.drop(game, player_move.Col_Num)
                            print()
                            common.board_display(game)
                     except:
                            print('Invalid Move')
              
                            
              elif player_move.Action == 'P':
                     try:
                            game = connectfour.pop(game, player_move.Col_Num)
                            print()
                            common.board_display(game)
                     except:
                            print('Invalid Move')
                            
              else:
                     print('Try again')
                     
              if winner(game):
                     break
Exemplo n.º 38
0
def new_game_state():
    '''New game state of ConnectFour'''
    return connectfour.new_game()
Exemplo n.º 39
0
def new_game_state():
    return connectfour.new_game()
Exemplo n.º 40
0
#Ryan Yue 69858941
#Hubert Cheng 12885496

import lab2_connectfourgame
import connectfour

def playGame(gamestate: connectfour.GameState):
	'''Calls functions from lab2_connectfourgame.py to play a console version of connectfour'''

	lab2_connectfourgame.printBoard(gamestate)
	while(lab2_connectfourgame.checkWin(gamestate)):
		user_action, col_num = lab2_connectfourgame.getUserInput()
		if (lab2_connectfourgame.checkMove(gamestate, user_action, col_num)):
			gamestate = lab2_connectfourgame.makeMove(gamestate, user_action, col_num)
			lab2_connectfourgame.printBoard(gamestate)
		else:
			print("Please enter a valid move")
	lab2_connectfourgame.printWinner(gamestate)

if __name__ == '__main__':
	playGame(connectfour.new_game())


Exemplo n.º 41
0
# Mahamadou Sylla

import connectfour
import sharedfunctions

game = connectfour.new_game()  # brand new game of connect four


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
Exemplo n.º 42
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'''
    
Exemplo n.º 43
0
import connectfour

rows = connectfour.BOARD_ROWS
columns = connectfour.BOARD_COLUMNS
new_board = connectfour.new_game()

def userInput():
##    game_board = new_board
##    while winner_is_chosen(game_board) == False:
    userInput = input('Please choose which column number from 1-7:\n').strip().lower()
    usercommand = userInput.split()
    if usercommand[0] == 'drop':
        pieces_drop = drop_piece(int(usercommand[1]) - 1)
        game_board = print_board(pieces_drop)
    elif usercommand[0] == 'pop':
        pop_piece(int(usercommand[1]) - 1)
    else:
        pass
            
def drop_piece(col_num: int):
    new_state = connectfour.drop(new_board, col_num)
    return new_state

def pop_piece(col_num: int):
    new_state = connectfour.pop(new_board, col_num)
    return pop_piece

def print_board(game_state):
    # this function will format the board later on
    print(game_state.board)
    board_state = game_state.board
Exemplo n.º 44
0
import connectfour
import collections

Move = collections.namedtuple('Move', ['Action', 'Col_Num'])

original_gamestate = connectfour.new_game()
game_state = connectfour.GameState
num = [1,2,3,4,5,6,7]


def board_display (gs: connectfour.GameState) -> None:
       '''
       Displays the board from the parameter GameState
       '''
       board = gs.board
       for pick in num:
              print(pick, end = '  ')
       print()
       for row in range(connectfour.BOARD_ROWS):
              for col in range(connectfour.BOARD_COLUMNS):
                     if board[col][row] == connectfour.NONE:
                            print('.', end = '  ')
                     if board[col][row] == connectfour.RED:
                            print('R', end = '  ')
                     if board[col][row] == connectfour.YELLOW:
                            print('Y', end = '  ')
              print()


def display_turn(gs: connectfour.GameState) -> str:
       '''Displays who's turn it is to play'''